def train_net(train_set, valid_set, test_set, in_dim, out_dim, cfg): # 在完整数据集上训练模型 train_loader, valid_loader, test_loader = make_loader( train_set, valid_set, test_set, seq_len=cfg['seq_len'], num_shift=cfg['num_shift'], bt_sz=cfg['bt_sz']) # 创建模型实例 net = RNN_Net(in_dim, cfg['hidden_dim'], out_dim, batchsize=cfg['bt_sz'], rnn_type=cfg['rnn_type'], num_layers=cfg['num_layers'], dropout=cfg['dropout'], bidirectional=cfg['bidirectional']) # 优化器定义 # opt = optim.RMSprop(net.parameters(), lr=cfg['lr_rate'], weight_decay=cfg['weight_decay']) # opt = AdaBoundW(net.parameters(), lr=cfg['lr_rate'], weight_decay=cfg['weight_decay']) opt = AdaBound(net.parameters(), lr=cfg['lr_rate'], weight_decay=cfg['weight_decay']) # 损失定义 criterion = nn.MSELoss() # 封装 model = Modeler(net, opt, criterion, set_device()) # 训练 for epoch in range(cfg['num_epoch']): train_loss = model.train_model(train_loader) # 当前 epoch 的训练损失 valid_loss = model.evaluate_model(valid_loader) # 当前 epoch 的验证损失 print( f"[{epoch + 1}/{cfg['num_epoch']}] ===>> train_loss: {train_loss: .4f} | valid_loss: {valid_loss: .4f}" ) # 训练结束 预测 prediction, err = model.predit_point_by_point(test_loader.dataset.data, test_loader.dataset.target) # 可视化预测效果 # for ch in range(prediction.shape[-1]): # plt.figure(figsize=(12, 5)) # plt.plot(np.c_[prediction.cpu().numpy()[:, ch], test_loader.dataset.target.cpu().numpy()[:, ch]]) # plt.legend([f'prediction channel{ch + 1}', f'label channel{ch + 1}']) # if cfg['vis']: # plt.show() return prediction, err
seqdata_all = get_mat_data(f'dev_seq_data/{signal_type}.mat', f'{signal_type}') # 读取数据 # 在完整数据集上训练模型 train_loader, valid_loader, test_loader = make_loader(seqdata_all, tt_split=0.7, tv_split=0.8, seq_len=seq_length, bt_sz=32) loaders = {'train': train_loader, 'valid': valid_loader} err_all = train_valid(2, 15, 2, test_loader.dataset.get_tensor_data(), loaders) # 基本设置 device = set_device() set1 = { 'longlag_nonlinear_signals': [3, 5, 8, 10, 12, 15, 18, 20], 'nonlinear_signals': [3, 5, 8, 10, 13, 15, 18, 20] } all_signal_type = ['nonlinear_signals', 'longlag_nonlinear_signals'] time_spend = {'longlag_nonlinear_signals': [], 'nonlinear_signals': []} for signal_type in all_signal_type: for seq_len in set1[signal_type]: print(f'{signal_type}, seq length: {seq_len}') timer = Timer() timer.start() main(seq_len) # 计时结束 b = timer.stop()