【问题标题】:Deep learning Udacity course: Prob 2 assignment 1 (notMNIST)深度学习 Udacity 课程:Prob 2 assignment 1 (notMNIST)
【发布时间】:2023-03-27 02:15:02
【问题描述】:

读完this并参加课程后,我正在努力解决作业1中的第二个问题(notMnist):

让我们验证数据是否仍然看起来不错。显示来自 ndarray 的标签和图像的样本。提示:你可以使用 matplotlib.pyplot。

这是我尝试过的:

import random
rand_smpl = [ train_datasets[i] for i in sorted(random.sample(xrange(len(train_datasets)), 1)) ]
print(rand_smpl)
filename = rand_smpl[0]
import pickle
loaded_pickle = pickle.load( open( filename, "r" ) )
image_size = 28  # Pixel width and height.
import numpy as np
dataset = np.ndarray(shape=(len(loaded_pickle), image_size, image_size),
                         dtype=np.float32)
import matplotlib.pyplot as plt

plt.plot(dataset[2])
plt.ylabel('some numbers')
plt.show()

但这就是我得到的:

这没有多大意义。老实说,我的代码也可能,因为我不确定如何解决这个问题!


泡菜是这样制作的:

image_size = 28  # Pixel width and height.
pixel_depth = 255.0  # Number of levels per pixel.

def load_letter(folder, min_num_images):
  """Load the data for a single letter label."""
  image_files = os.listdir(folder)
  dataset = np.ndarray(shape=(len(image_files), image_size, image_size),
                         dtype=np.float32)
  print(folder)
  num_images = 0
  for image in image_files:
    image_file = os.path.join(folder, image)
    try:
      image_data = (ndimage.imread(image_file).astype(float) - 
                    pixel_depth / 2) / pixel_depth
      if image_data.shape != (image_size, image_size):
        raise Exception('Unexpected image shape: %s' % str(image_data.shape))
      dataset[num_images, :, :] = image_data
      num_images = num_images + 1
    except IOError as e:
      print('Could not read:', image_file, ':', e, '- it\'s ok, skipping.')
    
  dataset = dataset[0:num_images, :, :]
  if num_images < min_num_images:
    raise Exception('Many fewer images than expected: %d < %d' %
                    (num_images, min_num_images))
    
  print('Full dataset tensor:', dataset.shape)
  print('Mean:', np.mean(dataset))
  print('Standard deviation:', np.std(dataset))
  return dataset

该函数的调用方式如下:

  dataset = load_letter(folder, min_num_images_per_class)
  try:
    with open(set_filename, 'wb') as f:
      pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL)

这里的想法是:

现在让我们以更易于管理的格式加载数据。因为,根据您的计算机设置,您可能无法将它们全部放入内存中,因此我们会将每个类加载到单独的数据集中,将它们存储在磁盘上并独立管理它们。稍后我们会将它们合并成一个大小可控的数据集。

我们会将整个数据集转换为浮点值的 3D 数组(图像索引,x,y),标准化为具有大约为零的均值和约 0.5 的标准差,以使训练更容易。

【问题讨论】:

  • 除非我们已注册课程,否则我们无法查看您的链接。请在您的问题中粘贴相关讨论。
  • @erip 感谢您的评论。 link 可以访问吗?嗯,你是对的。
  • 是的,评论的链接是可以访问的。
  • 好的,@erip!我还将代码编辑为最​​少。额外的代码是我解决的第一个问题的剩余代码(如果有帮助,我可以发布)。
  • 我认为你的大问题是你所做的一切都被声明为dataset(而不是初始化它)。它加载了垃圾值(在本例中为 0)。你没有在策划任何事情。如果没有更多数据或上下文,我不确定我们能做些什么。

标签: python matplotlib machine-learning computer-vision deep-learning


【解决方案1】:

使用此代码:

#random select a letter
i = np.random.randint( len(train_datasets) )
plt.title( "abcdefghij"[i] )

#read the file of selected letter
f = open( train_datasets[i], "rb" )
f = pickle.load(f)

#random select an image in the file
j = np.random.randint( len(f) )

#show image
plt.axis('off')
img = plt.imshow( f[ j, :, : ] )

enter image description here

【讨论】:

  • 哦,f[j] 得到同样的结果。酷!
【解决方案2】:

请检查此代码

pickle_file = train_datasets[0]
with open(pickle_file, 'rb') as f:

# unpickle
letter_set = pickle.load(f)  

# pick a random image index
sample_idx = np.random.randint(len(letter_set))

# extract a 2D slice
sample_image = letter_set[sample_idx, :, :]  
plt.figure()

# display it
plt.imshow(sample_image) 

【讨论】:

    【解决方案3】:

    按如下方式进行:

    #define a function to conver label to letter
    def letter(i):
        return 'abcdefghij'[i]
    
    
    # you need a matplotlib inline to be able to show images in python notebook
    %matplotlib inline
    #some random number in range 0 - length of dataset
    sample_idx = np.random.randint(0, len(train_dataset))
    #now we show it
    plt.imshow(train_dataset[sample_idx])
    plt.title("Char " + letter(train_labels[sample_idx]))
    

    您的代码实际上更改了数据集的类型,它不是大小为 (220000, 28,28) 的 ndarray

    一般来说,pickle 是一个包含一些对象的文件,而不是数组本身。您应该直接使用 pickle 中的对象来获取您的火车数据集(使用代码 sn-p 中的符号):

    #will give you train_dataset and labels
    train_dataset = loaded_pickle['train_dataset']
    train_labels = loaded_pickle['train_labels']
    

    更新:

    根据@gsarmas 的请求,我的整个Assignment1 解决方案的链接位于here

    代码被注释并且大部分是不言自明的,但如果有任何问题,请随时通过您喜欢的任何方式在 github 上联系

    【讨论】:

    • 另外,如果你愿意,我可以为你提供指向我的笔记本的链接,其中包含整个作业的解决方案,以便你可以将其用作示例
    • 哦,我明白了,所以我的代码并不算太糟糕,只是太糟糕了!是的,Maxim,那太好了,这样我就可以在遇到问题时使用它来解决问题。
    • @gsamaras 将在几个小时内将其发布到 git 并添加到此处。
    • Maxim 你不知道这会有多大帮助!我会发布一个错误,但如果你不确定我为什么会这样,让我对你将分享以解决的链接进行研究!我正在努力解决问题,但我收到了警告 @987654325 @ 然后train_dataset中出现错误:IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices
    • @gsamaras 我怀疑警告来自 rand_smpl 生成。您使用 random.sample 函数,从它的文档 (docs.scipy.org/doc/numpy/reference/generated/…) 中,您可以看到它返回浮点数,而不是整数。因此索引是错误的。
    猜你喜欢
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    相关资源
    最近更新 更多