tensorflow2.2_实现无高级封装——以训练MNIST为例


import tensorflow as tf

# 载入MNSIT数据集
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# ont-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)

# 定义数据集
train_data = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_data = train_data.repeat(1)
train_data = train_data.batch(32)

test_data = tf.data.Dataset.from_tensor_slices((x_test, y_test))
test_data = test_data.repeat(1)
test_data = test_data.batch(32)

# 定义模型
model = tf.keras.models.Sequential()

model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

# 定义优化器
optimizer = tf.keras.optimizers.SGD(0.1)

# 计算损失和准确率
train_loss = tf.keras.metrics.Mean(name='train_loss')
train_acc = tf.keras.metrics.CategoricalAccuracy(name='train_acc')

test_loss = tf.keras.metrics.Mean(name='test_loss')
test_acc = tf.keras.metrics.CategoricalAccuracy(name='test_acc')

# @tf.function装饰器来将python代码转成tensorflow的图表示代码,用于加速代码运行速度
# 定义训练函数
@tf.function
def train_step(data, label):
    with tf.GradientTape() as tape:
        predictions = model(data)
        loss = tf.keras.losses.MSE(label, predictions)
        # 传入loss和权值
        grad = tape.gradient(loss, model.trainable_variables)
        # 对权值进行调整
        optimizer.apply_gradients(zip(grad, model.trainable_variables))
        # 计算平均loss和准确率
        train_loss(loss)
        train_acc(label, predictions)

# 定义测试函数
@tf.function
def test_step(data, label):
    predictions = model(data)
    loss = tf.keras.losses.MSE(label, predictions)
    test_loss(loss)
    test_acc(label, predictions)

# 开始训练
for epoch in range(10):
    for img, label in train_data:
        train_step(img, label)
    for test_img, test_label in test_data:
        test_step(test_img, test_label)

    print('Epoch:%d, Loss:%.3f, Acc:%.3f, Test Loss:%.3f, Test Acc:%.3f'%(epoch, train_loss.result(), train_acc.result(), test_loss.result(), test_acc.result()))

训练结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值