1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| print('\n|' + '-' * 80+'\n') print("开始训练(名字)神经网络:\n") tu_test_loss=[] tu_train_loss=[] tu_train_yuce=[] tu_test_yuce=[] tu_train_day=[] tu_test_day=[] tu_train_re=[] tu_test_re=[] tu_x=[] for epoch in range(0, epochs): tu_x.append(epoch) train_loss = 0.0 # 一次完整迭代 enumerate将值变为索引:值 test_loss = 0.0 for (batch_index, batch) in enumerate(ce_shi): X2 = batch[0] Y2 = batch[1] Y_yuce2 = moxing(X2) loss_zhi2 = loss_func(Y_yuce2, Y2) # y 与 Y_yuce 仅有1个值,loss_zhi为仅有1值的张量 test_loss += loss_zhi2.item() loss_test = test_loss/len(ce_shi) # 计算平均测试损失 tu_test_loss.append(loss_test) pinggu_test = ping_gu(moxing, test_shuju, fenjie=0.5) tu_test_yuce.append(pinggu_test[1]) tu_test_day.append(pinggu_test[2]) tu_test_re.append(pinggu_test[3]) for (batch_index, batch) in enumerate(xun_lian): X = batch[0] Y = batch[1] Y_yuce = moxing(X) loss_zhi = loss_func(Y_yuce, Y) # y 与 Y_yuce 仅有1个值,loss_zhi为仅有1值的张量 train_loss += loss_zhi.item() # 累加张量的值 yiuhuaqi.zero_grad() # 重置所有梯度 loss_zhi.backward() # 计算新梯度 yiuhuaqi.step() # 更新所有权重 loss_train = train_loss/len(xun_lian) # 计算平均训练损失 pinggu_train = ping_gu(moxing, train_shuju, fenjie=0.5) tu_train_loss.append(loss_train) tu_train_yuce.append(pinggu_train[1]) tu_train_day.append(pinggu_train[2]) tu_train_re.append(pinggu_train[3]) if epoch > 0: plt.clf() plt.subplot(2, 2, 1) plt.plot(tu_x[1:], tu_train_loss[1:], label="训练误差", linestyle='-') plt.plot(tu_x[1:], tu_test_loss[1:], label="测试误差", linestyle='-') # plt.xlabel("遍历次数") # plt.ylabel("误差", fontsize=16) plt.title(f"训练误差 vs 测试误差") plt.legend(loc='center left') plt.subplot(2, 2, 2) plt.plot(tu_x[1:], tu_train_day[1:], label="训练指标3", linestyle='-') plt.plot(tu_x[1:], tu_test_day[1:], label="测试指标3", linestyle='-') # plt.xlabel("遍历次数") # plt.ylabel("指标3", fontsize=16) plt.title(f"训练指标3 vs 测试指标3") plt.tight_layout() plt.legend(loc='center left') plt.subplot(2, 2, 3) plt.plot(tu_x[1:], tu_train_yuce[1:], label="训练预测", linestyle='-') plt.plot(tu_x[1:], tu_test_yuce[1:], label="测试预测", linestyle='-') # plt.xlabel("遍历次数") # plt.ylabel("预测", fontsize=16) plt.title(f"训练预测 vs 测试预测") plt.tight_layout() plt.legend(loc='center left') plt.subplot(2, 2, 4) plt.plot(tu_x[1:], tu_train_re[1:], label="训练占比率", linestyle='-') plt.plot(tu_x[1:], tu_test_re[1:], label="测试占比率", linestyle='-') # plt.xlabel("遍历次数") # plt.ylabel("占比率", fontsize=16) plt.title(f"训练占比率 vs 测试占比率") plt.tight_layout() plt.legend(loc='center left') plt.pause(0.5) # 暂停一段时间,不然画的太快会卡住显示不出来 plt.ioff() # 关闭画图窗口
|