【发布时间】:2020-04-29 07:38:24
【问题描述】:
我正在尝试训练我的深度神经网络识别手写 数字,但我不断收到标题中所述的错误它 给我一个错误说:“ValueError:检查输入时出错: 预计 dense_7_input 有 2 维,但得到了形状的数组 (60000, 28, 28)”,我不知道为什么。我检查了以前的答案 解决这个问题,但没有任何效果。 新:所以当我尝试最后一段代码时,它给了我这个错误: ValueError:输入数组的样本数应与目标数组相同。找到 60000 个输入样本和 10000 个目标样本。
# 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)
# 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()
# 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
model = Sequential()
model.add(Dense(350, input_shape=input_shape, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# 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)
# New one #######
# 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]}%')
【问题讨论】:
-
你能告诉我们
dense_7_input是如何创建的吗? -
如果您的模型中的所有层都只有
Dense层并且您正在处理MNIST 数据集,那么您需要添加Flatten层作为模型的第一层。
标签: python tensorflow machine-learning keras deep-learning