深度学习Udacity课程:Prob 2作业1(不是MNIST)

时间:2016-07-04 16:35:50

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

阅读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()

但这就是我得到的:

enter image description here

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

泡菜的创建方式如下:

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,以使训练更容易。

3 个答案:

答案 0 :(得分:6)

执行以下操作:

#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)

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

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

更新:

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

代码被评论并且大部分都是不言自明的,但是如果有任何问题可以通过github以任何方式联系

答案 1 :(得分:1)

请查看此代码

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) 

Output

答案 2 :(得分: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