import tensorflow as tf
#加载mnist数据
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#改变测试集和训练集输入的形状,将二维图片变为一维向量
x_train = x_train.reshape(x_train.shape[0],28*28)
x_test = x_test.reshape(x_test.shape[0],x_test.shape[1]*x_test.shape[2])
#输出变为one-hot向量
y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)
y_test = tf.keras.utils.to_categorical(y_test, num_classes=10)
#构建网络
#定义网络模型
model = tf.keras.models.Sequential()
#定义网络层
layers1 = tf.keras.layers.Dense(500,activation='relu')
layers2 = tf.keras.layers.Dense(500,activation='relu')
layers3 = tf.keras.layers.Dense(10,activation='softmax')
#把网络加入模型
model.add(layers1)
model.add(layers2)
model.add(layers3)
#定义分类交叉熵损失函数
loss_function = tf.losses.categorical_crossentropy
#定义SGD优化器
optimizers = tf.optimizers.SGD(learning_rate=1e-3)
#模型编译
model.compile(optimizer = optimizers,loss = loss_function ,metrics = ['accuracy'])
#训练模型
model.fit(x_train,y_train,batch_size=128,epochs=20)
#评估模型
score = model.evaluate(x_test,y_test,batch_size=128)
print(score)
#保存模型
model.save('mnist_model.h5')
TensorFlow:MNIST手写数字识别模型训练
于 2023-07-12 14:46:10 首次发布