第二讲 神经网络优化 -- Adam
1 # 利用鸢尾花数据集,实现前向传播、反向传播,可视化loss曲线 2 3 # 导入所需模块 4 import numpy as np 5 import tensorflow as tf 6 from sklearn import datasets 7 from matplotlib import pyplot as plt 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 # 将打乱后的数据集分割为训练集和测试集,训练集为前120行,测试集为后30行 25 x_train = x_data[:-30] 26 y_train = y_data[:-30] 27 x_test = x_data[-30:] 28 y_test = y_data[-30:] 29 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使每次生成的随机数相同 43 w1 = tf.Variable(tf.random.truncated_normal([4, 3], stddev=0.1, seed=1)) 44 b1 = tf.Variable(tf.random.truncated_normal([3], stddev=0.1, seed=1)) 45 46 lr = 0.1 # 学习率为0.1 47 train_loss_results = [] # 将每轮的loss记录在此列表中,为后续画loss曲线提供数据 48 test_acc = [] # 将每轮的acc记录在此列表中,为后续画acc曲线提供数据 49 epoch = 500 # 循环500轮 50 loss_all = 0 # 每轮分4个step,loss_all记录四个step生成的4个loss的和 51 52 53 m_w, m_b = 0, 0 54 v_w, v_b = 0, 0 55 beta1, beta2 = 0.9, 0.999 56 delta_w, delta_b = 0, 0 57 global_step = 0 58 59 60 #训练部分 61 now_time = time.time() 62 for epoch in range(epoch): #数据集级别的循环,每个epoch循环一次数据集 63 for step, (x_train, y_train) in enumerate(train_db): # batch级别的循环 ,每个step循环一个batch 64 global_step += 1 65 with tf.GradientTape() as tape: # with结构记录梯度信息 66 y = tf.matmul(x_train, w1) + b1 # 神经网络乘加运算 67 y = tf.nn.softmax(y) # 使输出y符合概率分布(此操作后与独热码同量级,可相减求loss) 68 y_ = tf.one_hot(y_train, depth=3) # 将标签值转换为独热码格式,方便计算loss和accuracy 69 loss = tf.reduce_mean(tf.square(y_ - y)) # 采用均方误差损失函数mse = mean(sum(y-out)^2) 70 loss_all += loss.numpy() # 将每个step计算出的loss累加,为后续求loss平均值提供数据,这样计算的loss更准确 71 # 计算loss对各个参数的梯度 72 grads = tape.gradient(loss, [w1, b1]) 73 74 #Adam 75 m_w = beta1 * m_w + (1 - beta1) * grads[0] 76 m_b = beta1 * m_b + (1 - beta1) * grads[1] 77 v_w = beta2 * v_w + (1 - beta2) * tf.square(grads[0]) 78 v_b = beta2 * v_b + (1 - beta2) * tf.square(grads[1]) 79 80 m_w_correction = m_w / (1 - tf.pow(beta1, int(global_step))) 81 m_b_correction = m_b / (1 - tf.pow(beta1, int(global_step))) 82 v_w_correction = v_w / (1 - tf.pow(beta2, int(global_step))) 83 v_b_correction = v_b / (1 - tf.pow(beta2, int(global_step))) 84 85 w1.assign_sub(lr * m_w_correction / tf.sqrt(v_w_correction)) 86 b1.assign_sub(lr * m_b_correction / tf.sqrt(v_b_correction)) 87 88 89 #每个step,打印loss信息 90 print("Epoch {}, loss: {}".format(epoch, loss_all/4)) 91 train_loss_results.append(loss_all/4) # 将4个step的loss求平均记录在此变量中 92 loss_all = 0 # loss_all归零,为记录下一个epoch的loss做准备 93 94 95 #测试部分 96 # total_correct为预测对的样本个数, total_number为测试的总样本数,将这两个变量都初始化为0 97 total_correct, total_number = 0, 0 98 for x_test, y_test in test_db: 99 # 使用更新后的参数进行预测 100 y = tf.matmul(x_test, w1) + b1 101 y = tf.nn.softmax(y) 102 pred = tf.argmax(y, axis=1) # 返回y中最大值的索引,即预测的分类 103 # 将pred转换为y_test的数据类型 104 pred = tf.cast(pred, dtype = y_test.dtype) 105 # 若分类正确,则correct=1,否则为0,将bool型的结果转换为int型 106 correct = tf.cast(tf.equal(pred, y_test), dtype=tf.int32) 107 # 将每个batch的correct数加起来 108 correct = tf.reduce_sum(correct) 109 #将所有batch中的correct数加起来 110 total_correct += int(correct) 111 # total_number为测试的总样本数,也就是x_test的行数,shape[0]返回变量的行数 112 total_number += x_test.shape[0] 113 114 # 总的准确率等于total_correct/total_number 115 acc = total_correct / total_number 116 test_acc.append(acc) 117 print("Test acc:", acc) 118 print("--------------------------------------------") 119 120 total_time = time.time() - now_time 121 print("total_time", total_time) 122 123 124 125 # 绘制 loss 曲线 126 plt.title("Loss Function Curve") 127 plt.xlabel("Epoch") 128 plt.ylabel("Loss") 129 plt.plot(train_loss_results, label="$Loss$") 130 plt.legend() 131 plt.show() 132 133 # 绘制 Accuracy 曲线 134 plt.title("Acc Curve") 135 plt.xlabel("Epoch") 136 plt.ylabel("Acc") 137 plt.plot(test_acc, label="$Accuracy$") 138 plt.legend() 139 plt.show()