从 MNIST 数据集中提取 类

Extract classes from MNIST dataset

我正在使用 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)

我无法重现您的输出(代码会为我抛出错误),但您可以更简单:

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,然后我们使用它来获取相应的图像。