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