TensorFlow2.0官方教程复现笔记——初识TensorFlow

下载并安装 TensorFlow 2.0 测试版包。将 TensorFlow 载入你的程序:

# 载入tensorflow
import tensorflow as tf

载入并准备好 MNIST 数据集

# # 载入mnist数据集
mnist = tf.keras.datasets.mnist

如果下载mnist数据集失败可以手动导入,我将keras自带的datasets所有数据都下载下来了,下载网盘地址为

链接:https://pan.baidu.com/s/1D33j1kouqPtRQHFR_9o-fg
提取码:j283

将mnist数据集解压放在C:\Users\用户名\.keras\datasets\mnist下,其目录结构如下:

然后使用上面代码导入数据集,将数据集划分为训练集和测试集,并将样本从整数转换为浮点数(归一化->[0,1])

# 划分训练集,测试集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 将图片归一化->[0,1]
x_train, x_test = x_train / 255.0, x_test / 255.0

将模型的各层堆叠起来,以搭建 tf.keras.Sequential 模型。为训练选择优化器和损失函数:

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

训练并验证模型:

model.fit(x_train, y_train, batch_size=60000, epochs=5)
model.evaluate(x_test,  y_test, verbose=2)

使用batch_size=60000怎么也跑不到官网教程给的98%准确率,运行结果如下

batch_size=60000运行结果

使用batch_size=50能达到98%准确率,运行结果如下

batch_size=50运行结果

附录:完整代码

# -*- coding: utf-8 -*-
# @Time    : 2020/4/19 16:15
# @Author  : tone

# 载入tensorflow
import tensorflow as tf

# # 载入mnist数据集
mnist = tf.keras.datasets.mnist
import tensorflow as tf

# 划分训练集,测试集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 将图片归一化->[0,1]
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=50, epochs=5)
score = model.evaluate(x_test, y_test, verbose=2)
print(score)

发表评论

电子邮件地址不会被公开。 必填项已用*标注