import tensorflow as tf
# 引入mnist数据集
mnist = tf.keras.datasets.mnist
# 拆分训练数据, 训练数据对应标签, 测试数据, 测试数据对应标签
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 灰度值从0-255,归一化为0-1的数
x_train, x_test = x_train / 255.0, x_test / 2550
# tf.keras.models.Sequential 定义了神经网络结构
model = tf.keras.models.Sequential([
# Flatten 将输入数据转成一维
tf.keras.layers.Flatten(input_shape=(28, 28)),
# Dense 全连接层, 即每一个神经元都和前一层每一个神经元连接
tf.keras.layers.Dense(128, activation='relu'),
# Dropout 随机丢弃20%的神经元, 有效减少运算量并且一定程度避免过拟合
tf.keras.layers.Dropout(0.2),
# 经过dropout后再全连接层, 多分类问题使用 softmax 输出概率分布
tf.keras.layers.Dense(10, activation='softmax')
])
# 至此网络搭建完成, 配置优化器参数
# adam 作为优化器
# 交叉熵 作为损失函数
# 使用准确率来评价模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 开始训练参数
model.fit(x_train, y_train, epochs=5)
print(model.summary())
网友评论