【发布时间】:2020-04-29 12:32:02
【问题描述】:
我正在尝试训练我的深度神经网络识别手写 数字,但我不断收到标题中前面所述的错误它 给我一个错误说:ValueError:输入数组应该有 与目标数组相同数量的样本。找到 60000 个输入样本和 10000 个目标样本。我怎样才能解决这个问题? (我已经尝试过 train_test_split 和运输,但没有任何效果)
# Imports
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
# Configuration options
feature_vector_length = 784
num_classes = 60000
# Load the data
(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
# Reshape the data - MLPs do not understand such things as '2D'.
# Reshape to 28 x 28 pixels = 784 features
X_train = X_train.reshape(X_train.shape[0], feature_vector_length)
X_test = X_test.reshape(X_test.shape[0], feature_vector_length)
# Convert into greyscale
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
# Convert target classes to categorical ones
Y_train = to_categorical(Y_train, num_classes)
Y_test = to_categorical(Y_test, num_classes)
# Load the data
(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
# Visualize one sample
import matplotlib.pyplot as plt
plt.imshow(X_train[0], cmap='Greys')
plt.show()
# Set the input shape
input_shape = (feature_vector_length,)
print(f'Feature shape: {input_shape}')
# Create the model
# Using sigmoid instead of relu function
model = Sequential()
model.add(Flatten())
model.add(Dense(350, input_shape=input_shape, activation="sigmoid",
kernel_initializer=init))
model.add(Dense(50, activation="sigmoid", kernel_initializer=init))
model.add(Dense(num_classes, activation="sigmoid",
kernel_initializer=init))
# Configure the model and start training
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=
['accuracy'])
model.fit(X_train, Y_train, epochs=10, batch_size=250, verbose=1,
validation_split=0.2)
# Test the model after training
test_results = model.evaluate(X_test, Y_test, verbose=1)
print(f'Test results - Loss: {test_results[0]} - Accuracy:
{test_results[1]}%')
【问题讨论】:
-
我建议您首先花一些时间来清理您的代码。有些部分是重复的。尝试调试它。形状是你所期望的吗?最后说明:有大量关于 mnist 的 keras 教程。看看他们。
-
除上述内容外,请使用完整的错误跟踪更新您的问题 - 因为,即使错误发生的确切位置也无法说明。
-
无论如何,你不能拥有
num_classes = 60000! -
好的,我认为代码更简洁。实际上我试图将 num_classes 更改为 1000 但它仍然存在错误
-
你为什么认为你有
1000类?你检查过数据集中的内容吗?
标签: python tensorflow machine-learning keras deep-learning