1 # 利用鸢尾花数据集,实现前向传播、反向传播,可视化loss曲线
2
3 # 导入所需模块
4 import tensorflow as tf
5 from sklearn import datasets
6 from matplotlib import pyplot as plt
7 import numpy as np
8 import time
9
10
11 # 导入数据,分别为输入特征和标签
12 x_data = datasets.load_iris().data
13 y_data = datasets.load_iris().target
14
15 # 随机打乱数据(因为原始数据是顺序的,顺序不打乱会影响准确率)
16 # seed: 随机数种子,是一个整数,当设置之后,每次生成的随机数都一样(为方便教学,以保每位同学结果一致)
17 np.random.seed(116)
18 np.random.shuffle(x_data)
19 np.random.seed(116)
20 np.random.shuffle(y_data)
21 tf.random.set_seed(116)
22
23
24
25 # 将打乱后的数据集分割为训练集和测试集,训练集为前120行,测试集为后30行
26 x_train = x_data[:-30]
27 y_train = y_data[:-30]
28 x_test = x_data[-30:]
29 y_test = y_data[-30:]
30
31 # 转换x的数据类型,否则后面矩阵相乘时会因数据类型不一致报错
32 x_train = tf.cast(x_train, tf.float32)
33 x_test = tf.cast(x_test, tf.float32)
34
35 # from_tensor_slices函数使输入特征和标签值一一对应。(把数据集分批次,每个批次batch组数据)
36 train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32)
37 test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)
38
39
40 # 生成神经网络的参数,4个输入特征故,输入层为4个输入节点;因为3分类,故输出层为3个神经元
41 # 用tf.Variable()标记参数可训练
42 # 使用seed使每次生成的随机数相同(方便教学,使大家结果都一致,在现实使用时不写seed)
43
44 w1 = tf.Variable(tf.random.truncated_normal([4, 3], stddev=0.1, seed=1))
45 b1 = tf.Variable(tf.random.truncated_normal([3], stddev=1, seed=1))
46
47
48 lr = 0.1 # 学习率为0.1
49 train_loss_results = [] # 将每轮的loss记录在此列表中,为后续画loss曲线提供数据
50 test_acc = [] # 将每轮的acc记录在此列表中,为后续画acc曲线提供数据
51 epoch = 500 # 循环500轮
52 loss_all = 0 # 每轮分4个step,loss_all记录四个step生成的4个loss的和
53
54 m_w, m_b = 0, 0
55 beta = 0.9
56
57
58 # 训练部分
59 now_time = time.time()
60 for epoch in range(epoch):# 数据集级别的循环,每个epoch循环一次数据集
61 for step, (x_train, y_train) in enumerate(train_db):# batch级别的循环 ,每个step循环一个batch
62 with tf.GradientTape() as tape:# with结构记录梯度信息
63 y = tf.matmul(x_train, w1) + b1 # 神经网络乘加运算
64 y = tf.nn.softmax(y) # 使输出y符合概率分布(此操作后与独热码同量级,可相减求loss)
65 y_ = tf.one_hot(y_train, depth=3) # 将标签值转换为独热码格式,方便计算loss和accuracy
66 loss = tf.reduce_mean(tf.square(y_ - y)) # 采用均方误差损失函数mse = mean(sum(y-out)^2)
67 loss_all += loss.numpy()
68 # 计算loss对各个参数的梯度
69 grads = tape.gradient(loss, [w1, b1])
70
71 #sgd-momentun
72 m_w = beta * m_w + (1 - beta) * grads[0]
73 m_b = beta * m_b + (1 - beta) * grads[1]
74 w1.assign_sub(lr * m_w)
75 b1.assign_sub(lr * m_b)
76
77 # 每个epoch,打印loss信息
78 print("Epoch {}, loss: {}".format(epoch, loss_all / 4))
79 train_loss_results.append(loss_all / 4) # 将4个step的loss求平均记录在此变量中
80 loss_all = 0 # loss_all归零,为记录下一个epoch的loss做准备
81
82
83 # 测试部分
84 # total_correct为预测对的样本个数, total_number为测试的总样本数,将这两个变量都初始化为0
85 total_correct, total_number = 0, 0
86 for x_test, y_test in test_db:
87 #使用更新后的参数进行预测
88 y = tf.matmul(x_test, w1) + b1
89 y = tf.nn.softmax(y)
90 pred = tf.argmax(y, axis=1) # 返回y中最大值的索引,即预测的分类
91 # 将pred转换为y_test的数据类型
92 pred = tf.cast(pred, dtype=y_test.dtype)
93 # 若分类正确,则correct=1,否则为0,将bool型的结果转换为int型
94 correct = tf.cast(tf.equal(pred, y_test), dtype = tf.int32)
95 # 将每个batch的correct数加起来
96 correct = tf.reduce_sum(correct)
97 # 将所有batch中的correct数加起来
98 total_correct += int(correct)
99 # total_number为测试的总样本数,也就是x_test的行数,shape[0]返回变量的行数
100 total_number += x_test.shape[0]
101 # 总的准确率等于total_correct/total_number
102 acc = total_correct / total_number
103 test_acc.append(acc)
104 print("Test_acc:", acc)
105 print("------------------------------------")
106
107 total_time = time.time() - now_time
108 print("total_time", total_time)
109
110
111 # 绘制 loss 曲线
112 plt.title("Loss Function Curve")
113 plt.xlabel("Epoch")
114 plt.ylabel("Loss")
115 plt.plot(train_loss_results, label="$Loss$")
116 plt.legend()
117 plt.show()
118
119
120 # 绘制 Accuracy 曲线
121 plt.title("Acc Curve")
122 plt.xlabel("Epoch")
123 plt.ylabel("Acc")
124 plt.plot(test_acc, label="$Accuracy$")
125 plt.legend()
126 plt.show()