基于tf的前向传播(张量)

该博客通过TensorFlow实现了MNIST手写数字识别数据集的前向传播和梯度下降算法。首先,加载并预处理数据,接着初始化网络参数,然后进行10轮的训练,每轮中使用梯度下降更新权重。在训练过程中,将标签转为one-hot编码以计算损失,并输出每100个step的损失值。最后,计算并输出基于测试集的准确率。
摘要由CSDN通过智能技术生成

前向传播


基于现在的参数不断更新之前的参数

思路

  1. 加载数据集
  2. 数据集预处理(归一化,分配batch大小)
  3. 初始化参数与设定学习率
  4. 前向传播更新参数(梯度下降)(需要在此处改为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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值