前向传播
基于现在的参数不断更新之前的参数
思路
- 加载数据集
- 数据集预处理(归一化,分配batch大小)
- 初始化参数与设定学习率
- 前向传播更新参数(梯度下降)(需要在此处改为onehot编码,在此循环外改变编码会导致维度不一致)
代码
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets
# 取消多余的打印信息
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# 加载数据集
# x为[60k, 28, 28],值从0~255
# y为[60k],值从0~9
(x, y), (x_test, y_test) = datasets.mnist.load_data()
x = tf.convert_to_tensor(x, dtype=tf.float32) / 255.
y = tf.convert_to_tensor(y, dtype=tf.int32)
x_test = tf.convert_to_tensor(x_test, dtype=tf.float32) / 255.
y_test = tf.convert_to_tensor(y_test, dtype=tf.int32)
print(x.shape, x.dtype, y.shape, y.dtype)
print(tf.reduce_min(x), tf.reduce_max(x))
print(tf.reduce_min(y), tf.reduce_max(y))
# 分配batch大小为128,采样迭代方法循环元素
train_db = tf.data.Dataset.from_tensor_slices((x, y)).batch(128)
test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(128)
train_iter = iter(train_db)
sample = next(train_iter)
print('batch:', sample[0].shape, sample[1].shape)
# 初始化参数
# 层:28*28 -> 256 -> 128 -> 10
# 设定初始值方差,防止梯度爆炸
w1 = tf.Variable(tf.random.truncated_normal([784, 256], stddev=0.1))
b1 = tf.Variable(tf.random.truncated_normal([256]))
w2 = tf.Variable(tf.random.truncated_normal([256, 128], stddev=0.1))
b2 = tf.Variable(tf.random.truncated_normal([128]))
w3 = tf.Variable(tf.random.truncated_normal([128, 10], stddev=0.1))
b3 = tf.Variable(tf.random.truncated_normal([10]))
learning_rate = 1e-3
# 梯度下降前向传播
# 整个数据集循环10次
for epoch in range(10):
# 按batch循环整个数据集,其中step用于计数循环到第几个batch
for step, (x, y) in enumerate(train_db):
# x大小为[128,28,28],y大小为[128]
# 为了保持维度一致(保证矩阵间可计算),将x维度变为与第一个连接层维度一致
x = tf.reshape(x, [-1, 784])
# 梯度下降
with tf.GradientTape() as tape:
h1 = x @ w1 + b1
h1 = tf.nn.relu(h1)
h2 = h1 @ w2 + b2
h2 = tf.nn.relu(h2)
out = h2 @ w3 + b3
# 计算损失函数
# 将y编为独热码(循环外编码会导致维度不一致,原因未知)
y_onehot = tf.one_hot(y, depth=10)
loss = tf.square(y_onehot - out)
# 计算整体误差,如果计算每一个batch的误差,除以batch大小即可。如果求每一个元素具体的误差,除以batch大小后再除以独热码长度即可
loss = tf.reduce_mean(loss)
# 自动计算梯度
grades = tape.gradient(loss, [w1, b1, w2, b2, w3, b3])
# 更新每一个参数
w1.assign_sub(learning_rate * grades[0])
b1.assign_sub(learning_rate * grades[1])
w2.assign_sub(learning_rate * grades[2])
b2.assign_sub(learning_rate * grades[3])
w3.assign_sub(learning_rate * grades[4])
b3.assign_sub(learning_rate * grades[5])
# 打印每个100个step的信息
if step % 100 == 0:
print(epoch, step, 'loss:', float(loss))
# 计算准确率(基于测试集)
total_num = 0
total_correct = 0
for step, (x,y) in enumerate(test_db):
x = tf.reshape(x, [-1, 28*28])
h1 = tf.nn.relu(x @ w1 + b1)
h2 = tf.nn.relu(h1 @ w2 + b2)
out = h2 @ w3 + b3
# 将out缩放到0,1之间
prob = tf.nn.softmax(out, axis=1)
# 得出基于概率的预测值
pred = tf.argmax(prob, axis=1)
pred = tf.cast(pred, dtype=tf.int32)
correct = tf.cast(tf.equal(pred, y), dtype=tf.int32)
correct = tf.reduce_sum(correct)
# correct为numpy类型,需要转换为32位整形
total_correct += int(correct)
total_num += x.shape[0]
acc = total_correct / total_num
print('基于测试集的准确率:', acc)