如何从从 keras 导入的 MNIST 数据集中删除特定数字?

How can I remove a specific digit from the MNIST dataset imported from keras?

我正在尝试从 Keras 提供的 MNIST 数据集中删除特定数字(如 0、4)。

from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train.drop([0], axis = 1)
y_train.drop([0], axis = 1)

x_train_0 = x_trian[0]
y_train_0 = y_train[0]

结果报错:AttributeError: 'numpy.ndarray' object has no attribute 'drop'

我该怎么办?

另外,如果我想减去第0位的数据,我可以简单地做x_train[0]吗?

谢谢!!!

我们先看看Keras MNIST数据格式

>>> from keras.datasets import mnist
>>> (x_train, y_train), (x_test, y_test) = mnist.load_data()
>>> x_train.shape
(60000, 28, 28)
>>> y_train.shape
(60000,)

所以 x_... 变量保存图像,y_... 变量保存标签。它们都是 Numpy 数组对象。数据的顺序是什么?

>>> y_train[:20]
array([5, 0, 4, 1, 9, 2, 1, 3, 1, 4, 3, 5, 3, 6, 1, 7, 2, 8, 6, 9],
      dtype=uint8)

它们的顺序是随机的。这是一件好事,如果您只想通过连续切片来获取一小部分数据,则很容易获得包含每个数字的样本。但这会使您想完成的任务变得更加困难。您需要对应于每个数字的索引。然后你需要使用这些索引来select你想要的图像和标签。

您想查看名为 nonzero() 的 Numpy 数组方法,并且您会想了解 Numpy 如何使用布尔值数组 selecting 来自具有兼容形状的数组的元素。这个两行函数将满足您的需要:

def remove(digit, x, y):
    idx = (y != digit).nonzero()
    return x[idx], y[idx]

下面是如何调用它的示例:

x_no3, y_no3 = remove(3, x_train, y_train)