drop out, learning rate in nn

  1. use different initial learning rates, says: 1e-3, 1e-4, 1e-5, if 1e-5 is the best one, that means your network is too complicate. you may want reduce to the layers.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
return data, label def __len__(self): return len(self.data)train_dataset = MyDataset(train, y[:split_boundary].values, time_steps, output_steps, target_index)test_ds = MyDataset(test, y[split_boundary:].values, time_steps, output_steps, target_index)class MyLSTMModel(nn.Module): def __init__(self): super(MyLSTMModel, self).__init__() self.rnn = nn.LSTM(input_dim, 16, 1, batch_first=True) self.flatten = nn.Flatten() self.fc1 = nn.Linear(16 * time_steps, 120) self.relu = nn.PReLU() self.fc2 = nn.Linear(120, output_steps) def forward(self, input): out, (h, c) = self.rnn(input) out = self.flatten(out) out = self.fc1(out) out = self.relu(out) out = self.fc2(out) return outepoch_num = 50batch_size = 128learning_rate = 0.001def train(): print('训练开始') model = MyLSTMModel() model.train() opt = optim.Adam(model.parameters(), lr=learning_rate) mse_loss = nn.MSELoss() data_reader = DataLoader(train_dataset, batch_size=batch_size, drop_last=True) history_loss = [] iter_epoch = [] for epoch in range(epoch_num): for data, label in data_reader: # 验证数据和标签的形状是否满足期望,如果不满足,则跳过这个批次 if data.shape[0] != batch_size or label.shape[0] != batch_size: continue train_ds = data.float() train_lb = label.float() out = model(train_ds) avg_loss = mse_loss(out, train_lb) avg_loss.backward() opt.step() opt.zero_grad() print('epoch {}, loss {}'.format(epoch, avg_loss.item())) iter_epoch.append(epoch) history_loss.append(avg_loss.item()) plt.plot(iter_epoch, history_loss, label='loss') plt.legend() plt.xlabel('iters') plt.ylabel('Loss') plt.show() torch.save(model.state_dict(), 'model_1')train()param_dict = torch.load('model_1')model = MyLSTMModel()model.load_state_dict(param_dict)model.eval()data_reader1 = DataLoader(test_ds, batch_size=batch_size, drop_last=True)res = []res1 = []# 在模型预测时,label 的处理for data, label in data_reader1: data = data.float() label = label.float() out = model(data) res.extend(out.detach().numpy().reshape(data.shape[0]).tolist()) res1.extend(label.numpy().tolist()) # 由于预测一步,所以无需 reshape,直接转为 list 即可title = "t321"plt.title(title, fontsize=24)plt.xlabel("time", fontsize=14)plt.ylabel("irr", fontsize=14)plt.plot(res, color='g', label='predict')plt.plot(res1, color='red', label='real')plt.legend()plt.grid()plt.show()的运算过程
06-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值