def train_loop(): step = 0 ax = [] ay = [] plt.ion() PASS_NUM = n_epochs for pass_id in range(PASS_NUM): total_loss_pass = 0 for data in train_reader(): avg_loss_value, = exe.run( fluid.default_main_program(), feed= feeder.feed(data), fetch_list=[avg_loss]) total_loss_pass += avg_loss_value ax.append(pass_id) ay.append(total_loss_pass) plt.clf() plt.plot(ax, ay) plt.pause(0.01) plt.ioff() step += 1 display.clear_output(wait=True) fluid.io.save_inference_model(SAVE_DIRNAME, ['x'], [prediction], exe) train_loop()
时间: 2024-02-14 10:35:35 浏览: 29
这段代码定义了一个train_loop函数,用于训练模型。在函数内部,首先设置了迭代次数PASS_NUM和当前迭代次数pass_id,然后进入数据读取和训练的循环中。在每次循环中,通过train_reader函数读取一个mini-batch的训练数据,将数据送入计算图中进行前向计算和反向传播,得到平均损失值avg_loss_value。累计每个mini-batch的平均损失值,得到当前迭代次数下的总损失值total_loss_pass。将total_loss_pass和pass_id分别保存到ax和ay数组中,并使用matplotlib库将损失曲线实时显示在屏幕上。在训练完成后,使用fluid.io.save_inference_model函数将训练得到的模型保存到SAVE_DIRNAME目录中,以便后续的预测任务使用。请注意,这里的prediction是输出层的输出,即模型的预测结果。请问您还有其他问题吗?
相关问题
绘制训练集和测试集的真实值和预测值图像 train_predict_plot = np.empty_like(data_scaled) train_predict_plot[:, :] = np.nan train_predict_plot[time_steps:len(train_predict) + time_steps, :] = train_predict test_predict_plot = np.empty_like(data_scaled) test_predict_plot[:, :] = np.nan test_predict_plot[len(train_predict) + time_steps * 2 + 1:len(data_scaled) - 1, :] = test_predict plt.figure(figsize=(10, 6)) plt.plot(scaler.inverse_transform(data_scaled)) plt.plot(train_predict_plot) plt.plot(test_predict_plot) plt.legend(['True', 'Train Predict', 'Test Predict']) plt.xlabel('Time/h') plt.ylabel('kwh') plt.show(改写以上代码,使得训练集部分和测试集部分分别绘制在两张图上
下面是改写后的代码,将训练集和测试集的真实值和预测值分别绘制在两张图上:
```
train_predict_plot = np.empty_like(data_scaled)
train_predict_plot[:, :] = np.nan
train_predict_plot[time_steps:len(train_predict) + time_steps, :] = train_predict
test_predict_plot = np.empty_like(data_scaled)
test_predict_plot[:, :] = np.nan
test_predict_plot[len(train_predict) + time_steps * 2 + 1:len(data_scaled) - 1, :] = test_predict
# 绘制训练集部分真实值和预测值图像
plt.figure(figsize=(10, 6))
plt.plot(scaler.inverse_transform(data_scaled[:len(train_predict)]))
plt.plot(train_predict_plot[:len(train_predict)])
plt.legend(['True', 'Train Predict'])
plt.xlabel('Time/h')
plt.ylabel('kwh')
plt.title('Training Set')
plt.show()
# 绘制测试集部分真实值和预测值图像
plt.figure(figsize=(10, 6))
plt.plot(scaler.inverse_transform(data_scaled[len(train_predict) + time_steps * 2 + 1:]))
plt.plot(test_predict_plot[len(train_predict) + time_steps * 2 + 1:])
plt.legend(['True', 'Test Predict'])
plt.xlabel('Time/h')
plt.ylabel('kwh')
plt.title('Test Set')
plt.show()
```
class RandomWalk(): def __init__(self,point_num=5000): self.point_num = point_num self.xval = [0] self.yval = [0] def fill_walk(self): while len(self.xval)<self.point_num: x_direction = choice([1,-1]) step_num = choice([0,1,2,3,4]) xstep = x_direction * step_num y_direction = choice([1,-1]) step_num = choice([0,1,2,3,4]) ystep = y_direction * step_num if xstep == 0 and ystep==0: continue x_next = self.xval[-1] + xstep y_next = self.yval[-1] + ystep self.xval.append(x_next) self.yval.append(y_next) rw = RandomWalk(50000) rw.fill_walk() point_numbers = list(range(rw.point_num())) plt.scatter(rw.x_val,rw.y_val,c=point_numbers,cmap=plt.cm.Blues,edgecolor = 'none',s=2) plt.scatter(0,0,c='green',edgecolors='none',s=100) plt.scatter(rw.x_val[-1],rw.y_val[-1],c='red',edgecolor='none',s=100) plt.axes().get_xaxis().set_visible(False) plt.axes().get_xaxis().set_yisible(False) plt.show()修改代码
以下是修改后的代码:
```python
import matplotlib.pyplot as plt
from random import choice
class RandomWalk():
def __init__(self, point_num=5000):
self.point_num = point_num
self.x_val = [0]
self.y_val = [0]
def fill_walk(self):
while len(self.x_val) < self.point_num:
x_direction = choice([1, -1])
x_step = choice([0, 1, 2, 3, 4])
x_val = x_direction * x_step
y_direction = choice([1, -1])
y_step = choice([0, 1, 2, 3, 4])
y_val = y_direction * y_step
if x_val == 0 and y_val == 0:
continue
next_x = self.x_val[-1] + x_val
next_y = self.y_val[-1] + y_val
self.x_val.append(next_x)
self.y_val.append(next_y)
rw = RandomWalk(50000)
rw.fill_walk()
point_numbers = list(range(rw.point_num))
plt.scatter(rw.x_val, rw.y_val, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=2)
plt.scatter(0, 0, c='green', edgecolors='none', s=100)
plt.scatter(rw.x_val[-1], rw.y_val[-1], c='red', edgecolor='none', s=100)
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
```
主要的修改包括:
1. `xval` 和 `yval` 改为 `x_val` 和 `y_val`,以符合 Python 的命名规范。
2. `rw.point_num()` 改为 `rw.point_num`,因为 `point_num` 是一个属性而不是方法。
3. `plt.axes().get_xaxis().set_yisible(False)` 改为 `plt.axes().get_yaxis().set_visible(False)`,因为原来的代码中打错了单词。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)