当前位置:   article > 正文

李宏毅2023机器学习作业1--homework1——模型创建

李宏毅2023机器学习作业1--homework1——模型创建

一、导入包

  1. import torch # pytorch
  2. import torch.nn as nn
  3. from torch.utils.data import Dataset, DataLoader, random_split

二、配置项

方便更新超参数,对模型进行参数调整

  1. device = 'cuda' if torch.cuda.is_available() else 'cpu'
  2. config = {
  3. 'seed': 5201314, # Your seed number, you can pick your lucky number. :)
  4. 'select_all': False, # Whether to use all features.
  5. 'valid_ratio': 0.2, # validation_size = train_size * valid_ratio
  6. 'n_epochs': 5000, # Number of epochs.
  7. 'batch_size': 256,
  8. 'learning_rate': 1e-5,
  9. 'early_stop': 600, # If model has not improved for this many consecutive epochs, stop training.
  10. 'save_path': './models/model.ckpt' # Your model will be saved here.
  11. }

三、创建神经网络模型

  1. class My_Model(nn.Module): # 搭建的神经网络 Model继承了 Module类(父类)
  2. def __init__(self, input_dim): # 初始化函数
  3. super(My_Model, self).__init__() # 必须要这一步,调用父类的初始化函数
  4. # TODO: modify model's structure, be aware of dimensions.
  5. self.layers = nn.Sequential(
  6. nn.Linear(input_dim, 16),
  7. nn.ReLU(),
  8. nn.Linear(16, 8),
  9. nn.ReLU(),
  10. nn.Linear(8, 1)
  11. )
  12. def forward(self, x): # 前向传播(为输入和输出中间的处理过程),x为输入
  13. x = self.layers(x)
  14. x = x.squeeze(1) # (B, 1) -> (B)
  15. return x

四、模型训练过程

  1. def trainer(train_loader, valid_loader, model, config, device):
  2. criterion = nn.MSELoss(reduction='mean') # Define your loss function, do not modify this.
  3. # Define your optimization algorithm.
  4. # TODO: Please check https://pytorch.org/docs/stable/optim.html to get more available algorithms.
  5. # TODO: L2 regularization (optimizer(weight decay...) or implement by your self).
  6. optimizer = torch.optim.SGD(model.parameters(), lr=config['learning_rate'], momentum=0.9)
  7. # math.inf为无限大
  8. n_epochs, best_loss, step, early_stop_count = config['n_epochs'], math.inf, 0, 0
  9. for epoch in range(n_epochs):
  10. model.train() # Set your model to train mode.
  11. loss_record = [] # 记录损失
  12. for x, y in train_loader:
  13. optimizer.zero_grad() # Set gradient to zero. 梯度清0
  14. x, y = x.to(device), y.to(device) # Move your data to device.
  15. pred = model(x) # 数据传入模型model,生成预测值pred
  16. loss = criterion(pred, y) # 预测值pred和真实值y计算损失loss
  17. loss.backward() # Compute gradient(backpropagation).
  18. optimizer.step() # Update parameters.
  19. step += 1
  20. loss_record.append(loss.detach().item()) # 当前步骤的loss加到loss_record[]
  21. # Display current epoch number and loss on tqdm progress bar.
  22. train_pbar.set_description(f'Epoch [{epoch+1}/{n_epochs}]')
  23. train_pbar.set_postfix({'loss': loss.detach().item()})
  24. mean_train_loss = sum(loss_record)/len(loss_record) # 计算训练集上平均损失
  25. writer.add_scalar('Loss/train', mean_train_loss, step)
  26. model.eval() # Set your model to evaluation mode.
  27. loss_record = []
  28. for x, y in valid_loader:
  29. x, y = x.to(device), y.to(device)
  30. with torch.no_grad():
  31. pred = model(x)
  32. loss = criterion(pred, y)
  33. loss_record.append(loss.item())
  34. mean_valid_loss = sum(loss_record)/len(loss_record) # 计算验证集上平均损失
  35. print(f'Epoch [{epoch+1}/{n_epochs}]: Train loss: {mean_train_loss:.4f}, Valid loss: {mean_valid_loss:.4f}')
  36. writer.add_scalar('Loss/valid', mean_valid_loss, step)
  37. # 保存验证集上平均损失最小的模型
  38. if mean_valid_loss < best_loss:
  39. best_loss = mean_valid_loss
  40. torch.save(model.state_dict(), config['save_path']) # Save your best model
  41. print('Saving model with loss {:.3f}...'.format(best_loss))
  42. early_stop_count = 0
  43. else:
  44. early_stop_count += 1
  45. # 设置早停early_stop_count
  46. # 如果early_stop_count次数,验证集上的平均损失没有变化,模型性能没有提升,停止训练
  47. if early_stop_count >= config['early_stop']:
  48. print('\nModel is not improving, so we halt the training session.')
  49. return

五、训练模型

  1. # 创建模型model,将模型和数据放到相同的计算设备上
  2. model = My_Model(input_dim=x_train.shape[1]).to(device)
  3. # 开始训练
  4. trainer(train_loader, valid_loader, model, config, device)

六、模型测试过程

  1. # 测试数据集的预测
  2. def predict(test_loader, model, device):
  3. model.eval() # Set your model to evaluation mode.
  4. preds = []
  5. for x in tqdm(test_loader):
  6. x = x.to(device)
  7. with torch.no_grad(): # 关闭梯度
  8. pred = model(x)
  9. preds.append(pred.detach().cpu())
  10. preds = torch.cat(preds, dim=0).numpy()
  11. return preds

七、测试模型

  1. def save_pred(preds, file):
  2. ''' Save predictions to specified file '''
  3. with open(file, 'w') as fp:
  4. writer = csv.writer(fp)
  5. writer.writerow(['id', 'tested_positive'])
  6. for i, p in enumerate(preds):
  7. writer.writerow([i, p])
  8. model = My_Model(input_dim=x_train.shape[1]).to(device)
  9. model.load_state_dict(torch.load(config['save_path'])) # 加载模型
  10. preds = predict(test_loader, model, device) # 生成预测结果preds
  11. save_pred(preds, 'pred.csv') # 保存preds到pred.csv

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/166301?site
推荐阅读
相关标签
  

闽ICP备14008679号