import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.utils import to_categorical # 1.读取数据集 (x_train, y_train), (x_test, y_test) = mnist.load_data() # 将图像数据转换为float32类型 x_train = x_train.astype('float32') x_test = x_test.astype('float32') # 归一化图像数据 x_train /= 255 x_test /= 255 # 2.将y标签转为独热编码格式 y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10) # 3.创建模型 model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(600, activation='relu'), tf.keras.layers.Dropout(0.3), tf.keras.layers.Dense(400, activation='relu'), tf.keras.layers.Dropout(0.3), tf.keras.layers.Dense(200, activation='relu'), tf.keras.layers.Dropout(0.3), tf.keras.layers.Dense(10, activation='softmax') ]) # 搭建模型 model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, batch_size=256, epochs=20, validation_split=0.2) test_loss, test_acc = model.evaluate(x_test, y_test) print('Test accuracy:', test_acc)请帮我给代码添加注释
时间: 2024-02-21 18:57:22 浏览: 24
好的,以下是注释后的代码:
```python
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
# 1.读取数据集
# 载入mnist数据集,包括训练集和测试集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 将图像数据转换为float32类型
# 将训练集和测试集的图像数据类型转换为float32
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
# 归一化图像数据
# 将训练集和测试集的图像数据归一化
x_train /= 255
x_test /= 255
# 2.将y标签转为独热编码格式
# 将训练集和测试集的标签进行独热编码
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# 3.创建模型
# 创建一个序列模型,包含一个输入层、三个隐藏层和一个输出层
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)), # 输入层,将输入的28*28的图像展开为一维向量
tf.keras.layers.Dense(600, activation='relu'), # 第一个隐藏层,包含600个神经元,使用relu作为激活函数
tf.keras.layers.Dropout(0.3), # 第一个隐藏层后添加一个dropout层,防止过拟合
tf.keras.layers.Dense(400, activation='relu'), # 第二个隐藏层,包含400个神经元,使用relu作为激活函数
tf.keras.layers.Dropout(0.3), # 第二个隐藏层后添加一个dropout层,防止过拟合
tf.keras.layers.Dense(200, activation='relu'), # 第三个隐藏层,包含200个神经元,使用relu作为激活函数
tf.keras.layers.Dropout(0.3), # 第三个隐藏层后添加一个dropout层,防止过拟合
tf.keras.layers.Dense(10, activation='softmax') # 输出层,包含10个神经元,使用softmax作为激活函数,进行多分类
])
# 4.配置模型并进行训练,其中测试集比例为0.2
# 配置模型的优化器、损失函数和评价指标,然后使用训练集进行训练,其中测试集比例为0.2
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=256, epochs=20, validation_split=0.2)
# 5.训练完成后,测试机准确率在0.98以上
# 使用测试集进行验证,输出测试准确率
test_loss, test_acc = model.evaluate(x_test, y_test)
print('Test accuracy:', test_acc)
```