1.本文介绍
本文主要讲解是用TF2.0创建前向网络。主要是前向网络的程序讲解。使用本文程序要安装本文使用的库,keras、datasets、os。
2.程序部分
2.1创建数据集
#首先导入需要的库
import tensorflow ad tf
from tensorflow import keras
from tensorflow.keras import datasets
import os
#屏蔽一些不必要的输出,0代表输出所有信息,2代表只输出错误信息
os.environ['TF_CPP_LOG_LEVEL'] = '2'
#加载数据集
#x:[60k,28,28]
#y:[60k]
(x,y),= datasets.mnist.load_data()
#把数据集转换为张量
x=tf.convert_to_tensor(x, dtype=tf.float32)
y=tf.convert_to_tensor(y, dtype=tf.int32)
#输出x和y的大小以及数据类型
print(x,shape, y.shape, x.dtype, y.dtype)
#输出x和y的最大最小值
print(tf.reduce_min(x), tf.reduce_max(x))
print(tf.reduce_min(y), tf.reduce_max(y))
#设置batch
train_db = tf.data.Dataset.from_tensor_slices((x,y)).batch(128)
#设置迭代,遍历这个数据集的图片
train_iter = iter(train_db)
sample = next(train_iter)
#输出batch的大小,sample[0]代表batch中的x,sample[1]代表batch中的y
print('batch:',sample[0].shape, sample[1].shape)
2.2权重设置
w1 = tf.Variable(tf.random.truncated_normal([784,256], stddev = 0.1))
b1 = tf.Variable(tf.zeros([256]))
w2 = tf.Variable(tf.random.truncated_normal([256,128], stddev = 0.1))
b2 = tf.Variable(tf.zeros([128]))
w3 = tf.Variable(tf.random.truncated_normal([128,10], stddev = 0.1))
b3 = tf.Variable(tf.zeros([10]))
2.3前向传播
for step,(x, y) in enumerate(train_db):
#batch中的x为[128, 28 ,28]
#batch中的y为[128]
#使用维度变换把x转换为[b, 28, 28]
x = tf.reshape(x, [-1, 28*28])
#x:[b,28*28]
#h1 = x@w1 + b1
#[b, 784]@[784, 256] + [256] => [b, 256] + [256]
#设置梯度更新
with tf.GradientTape() as tape:
#使用broadcast为数据添加轴,因加号前边的数据有两个轴,不使用broadcast也可以,因为加号可以自动加轴,本文写出来主要是为了大家方便理解
h1 = x@w1 + tf.broadcast_to (b1,[x.shape[0], 256])
h1 = tf.nn.relu(h1)
#[b, 256]=>[b,128]
h2 = h1@w2 + b2
h2 = tf.nn.relu(h2)
#[b, 128] => [b,10]
out = h2@w3 + b3
#把y从tensor转换为onehot,否则无法进行计算
y_onehot = tf.one_hot(y, depth=10)
#计算均方误差
loss = tf.square(y_onehot - out)
#计算loss均值
loss = tf.reduce_mean(loss)
#计算梯度
grads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3])
#设置学习率为0.001,并且更新参数
lr = 1e-3
w1.assign_sub(lr * grads[0])
b1.assign_sub(lr * grads[1])
w2.assign_sub(lr * grads[2])
b2.assign_sub(lr * grads[3])
w3.assign_sub(lr * grads[4])
b3.assign_sub(lr * grads[5])
#查看每100步的Loss
if step%100 == 0
print(step, 'loss:', float(loss))