【问题标题】:How to select a desired training sample from mnist.load_data()如何从 mnist.load_data() 中选择所需的训练样本
【发布时间】:2023-08-12 03:00:02
【问题描述】:

这里是机器学习的新手。我正在尝试训练 1000 对训练数据和 500 对测试数据,而不是整个数据集。但是,我收到了错误:

“ValueError:检查目标时出错:预期activation_24 的形状为(10,),但得到的数组的形状为(1,)”

这是我与数据相关的部分代码:

# load data
(X_train, y_train), (X_test, y_test) = mnist.load_data()

X_train = X_train / 255
X_test = X_test / 255

X_train = X_train.reshape(-1,1,28,28) 
X_train = X_train[:1000,:,:]
X_test = X_test[:500,:,:]


y_train = y_train[:1000]
y_test  = y_test[:500]

X_test = np.array(X_test)
X_test = X_test.reshape(-1,1,28,28) 

print('X_train shape: ',X_train.shape)
print('X_test shape: ',np.shape(X_test ))
print('y_train shape: ',y_train.shape)
print('y_test shape: ',np.shape(y_test ))

输出:

X_train 形状:(1000, 1, 28, 28) X_test 形状:(500, 1, 28, 28) y_train 形状:(1000,) y_test 形状:(500,)

我在这方面做得对吗?还有其他方法可以实现目标吗? 提前致谢

【问题讨论】:

    标签: python tensorflow keras deep-learning mnist


    【解决方案1】:

    从训练集中取出前 1000 个,从测试集中取出 500 个,只需要这样:

    X_train = X_train[:1000].reshape(1000,28,28,1)
    y_train = y_train[:1000].reshape(1000,1)
    
    X_test = X_test[:500].reshape(500,28,28,1)
    y_test = y_test[:500].reshape(500,1)
    

    Keras 默认使用最后一个通道,因此 (batch, 28, 28, 1)。 对于 y,数据需要从 (batch,) 整形到 (batch,1)。 您还可以使用 [:batch] 从第一个维度获取元素并在同一行上进行整形。

    【讨论】:

      【解决方案2】:

      X_train 不应该是形状 (1000, 1, 28, 28)。

      使用 Keras 的“channels_last”格式,您的数据形状应该是 (Batch x Height x Width x Channel) 所以 (1000,28,28,1)。

      看看这个例子:https://keras.io/examples/mnist_cnn/

      【讨论】:

        最近更新 更多