我正在使用MNIST数据集,并且正在研究数据以绘制它们,但是在尝试从数据集中提取不同的类时遇到了问题。
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=False)
dataWithLabels = zip(mnist.train.labels, mnist.train.images)
digitDict = {}
for i in range(0,10):
digitDict[i] = []
for i in dataWithLabels:
digitDict[i[0][0]].append(i[1])
for i in range(0,10):
digitDict[i] = np.matrix(digitDict[i])
print("Digit {0} matrix shape: {1}".format(i,digitDict[i].shape))
输出为:
Digit 0 matrix shape: (49556, 784)
Digit 1 matrix shape: (5444, 784)
Digit 2 matrix shape: (1, 0)
Digit 3 matrix shape: (1, 0)
Digit 4 matrix shape: (1, 0)
Digit 5 matrix shape: (1, 0)
Digit 6 matrix shape: (1, 0)
Digit 7 matrix shape: (1, 0)
Digit 8 matrix shape: (1, 0)
Digit 9 matrix shape: (1, 0)
但是应该是:
Digit 0 matrix shape: (5444, 784)
Digit 1 matrix shape: (6179, 784)
Digit 2 matrix shape: (5470, 784)
Digit 3 matrix shape: (5638, 784)
Digit 4 matrix shape: (5307, 784)
Digit 5 matrix shape: (4987, 784)
Digit 6 matrix shape: (5417, 784)
Digit 7 matrix shape: (5715, 784)
Digit 8 matrix shape: (5389, 784)
Digit 9 matrix shape: (5454, 784)
答案 0 :(得分:0)
我无法复制您的输出(代码对我抛出错误),但是您可以更简单地完成此操作:
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=False)
digitDict = {}
for i in range(10):
mask = (mnist.train.labels == i)
digitDict[i] = mnist.train.images[mask]
for i in range(10):
print("Digit {0} matrix shape: {1}".format(i,digitDict[i].shape))
这应该比您的版本更有效。 mnist.train.labels == i
提供了一个布尔数组,向您显示该数组的哪些条目等于i
,然后我们用它来获取对应的图像。