报错原因:
ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (32, 28, 28)
以下是原代码:
import tensorflow as tf
import pandas as pd#导入数据分析工具包pandas
import numpy as np
import tensorflow as tf
# 读取数据
data = np.load('mnist.npz')
data.files
train_images, train_labels, test_images, test_labels = data['x_train'], data['y_train'], data['x_test'], data['y_test']
print(train_images.shape)
print(train_labels.shape)
print(test_images.shape)
print(test_labels.shape)
# 交叉熵
# target_y: 0 -> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# predicted_y1: 1 -> [0.4, 0.5, 0.1, 0, 0, 0, 0, 0, 0, 0]
# predicted_y2: 2 -> [0.1, 0.2, 0.7, 0, 0, 0, 0, 0, 0, 0]
target_y = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0])
predicted_y1 = np.array([0.4, 0.5, 0.1, 0, 0, 0, 0, 0, 0, 0])
predicted_y2 = np.array([0.1, 0.2, 0.7, 0, 0, 0, 0, 0, 0, 0])
-np.sum(target_y*np.log(predicted_y1+0.0000001))
-np.sum(target_y*np.log(predicted_y2+0.0000001))
# 搭建网络结构
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=32, kernel_size=3, padding='same', activation='relu'),
tf.keras.layers.Conv2D(filters=64, kernel_size=3, padding='same', activation='relu'),
tf.keras.layers.Conv2D(filters=64, kernel_size=3, padding='same', activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(train_images, train_labels, verbose=1, epochs=20, validation_data=(test_images, test_labels))
model.save('model_mnist.h5') # 保存模型