【发布时间】:2019-09-15 16:57:01
【问题描述】:
我在 python 3.6 上运行以下代码:
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float')/255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float')/255
train_labels = ku.to_categorical(train_labels)
test_labels = ku.to_categorical(test_labels)
filepath = 'my_model_file.hdf5' # define where the model is saved
callbacks_list = [
keras.callbacks.EarlyStopping(
monitor = 'val_loss', # Use accuracy to monitor the model
patience = 1 # Stop after one step with lower accuracy
),
keras.callbacks.ModelCheckpoint(
filepath = filepath, # file where the checkpoint is saved
monitor = 'val_loss', # Don't overwrite the saved model unless val_loss is worse
save_best_only = True # Only save model if it is the best
)
]
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu', kernel_regularizer=l2(0.001)))
model.add(Dropout(0.5))
model.add(layers.Dense(10, activation='softmax'))
model.summary()
## Compile the model
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
## Now fit the model
nr.seed(2356)
set_random_seed(2333)
history = model.fit(train_images, train_labels, epochs=40, batch_size = 128, callbacks = callbacks_list, validation_data = (test_images, test_labels)) # Call backs argument here)
并得到以下错误:
ValueError: Error when checking target: expected dense_5 to have shape (None, 1) but got array with shape (60000, 10)
我之前看到的关于数据标签的帖子应该转换为分类数据,但已经完成了。实际上大部分代码都是从张量流教程中复制过去的,所以很难看出哪里出了问题。
【问题讨论】:
标签: python-3.x tensorflow keras conv-neural-network