视频链接
PDF链接
googleColab链接
GoogleColab是一个免费的jupyter notebook,可以用上面的gpu资源进行训练
题目
通过前两天的数据,预测第三天某个人感染新冠的概率
范例
导包
# Numerical Operations
import math
import numpy as np# Reading/Writing Data
import pandas as pd
import os
import csv# For Progress Bar
from tqdm import tqdm# Pytorch
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader, random_split# For plotting learning curve
from torch.utils.tensorboard import SummaryWriter
工具
def same_seed(seed): '''Fixes random number generator seeds for reproducibility.'''# 输入相同的数据,输出同样的结果torch.backends.cudnn.deterministic = True# 不进行卷积自动优化,保证计算结果是相同的torch.backends.cudnn.benchmark = False# 分别为Numpy,pytorch和所有GPU设置随机种子np.random.seed(seed)torch.manual_seed(seed)if torch.cuda.is_available():torch.cuda.manual_seed_all(seed)# 将提供的数据划分为训练集和验证集
def train_valid_split(data_set, valid_ratio, seed):'''Split provided training data into training set and validation set'''valid_set_size = int(valid_ratio * len(data_set)) train_set_size = len(data_set) - valid_set_size# 随机划分train_set_size个元素为训练集,valid_set_size哥元素为验证集train_set, valid_set = random_split(data_set, [train_set_size, valid_set_size], generator=torch.Generator().manual_seed(seed))return np.array(train_set), np.array(valid_set)# 预测测试数据
def predict(test_loader, model, device):# 设置为评估模式,评估模式的意义是啥?model.eval() # Set your model to evaluation mode.preds = []# 遍历test_loader数据,使用tqdm显示循环进度for x in tqdm(test_loader):# 将x放到device中x = x.to(device)# 禁用梯度计算,因为在预测阶段根本不需要这个,浪费资源 with torch.no_grad(): # 进行预测pred = model(x) # 使用detch()将预测结果从计算图中分离,然后使用cpu()将结果移动到CPU中,最后追加到preds列表 preds.append(pred.detach().cpu()) # torch.cat()将所有预测结果沿着第0个维度链接起来(即行拼接),然后使用numpy()转成numpy数组preds = torch.cat(preds, dim=0).numpy() return preds
定义数据集类
# 数据集类,处理和加载用于训练模型或者进行预测的数据
class COVID19Dataset(Dataset):'''x: Features.y: Targets, if none, do prediction.'''def __init__(self, x, y=None):if y is None:self.y = yelse:self.y = torch.FloatTensor(y)self.x = torch.FloatTensor(x)def __getitem__(self, idx):if self.y is None:return self.x[idx]else:return self.x[idx], self.y[idx]def __len__(self):return len(self.x)
定义神经网络模型
# 模型定义,继承自pytorch的nn.Moudule基类(所有神经网络的基类)
class My_Model(nn.Module):def __init__(self, input_dim):# 调用父类的构造函数(必须)super(My_Model, self).__init__()# TODO: modify model's structure, be aware of dimensions. # 定义自己的模型,nn.Sequential是一个容器,按顺序包含一系列的层,这里定义了三个连接层和两个激活函数# 这里的激活函数是ReLu(),意思是如果nn.Linear()的结果小于0,则神经网络不继续往下走,用于缓解梯度消失问题self.layers = nn.Sequential(nn.Linear(input_dim, 16),nn.ReLU(),nn.Linear(16, 8),nn.ReLU(),nn.Linear(8, 1))# 定义了模型的前向传播过程,用于预测def forward(self, x):# 将x放到上面定义的模型中计算x = self.layers(x)# 再去掉x的第二维度,减少不必要的维度,使得张量的形状更适合接下来的计算?为啥x = x.squeeze(1) # (B, 1) -> (B)return x
选择特征
# 选择特征来执行回归
def select_feat(train_data, valid_data, test_data, select_all=True):'''Selects useful features to perform regression'''# 选取所有行的最后一列的数据y_train, y_valid = train_data[:,-1], valid_data[:,-1]# 选取所有行的除了最后一列的数据raw_x_train, raw_x_valid, raw_x_test = train_data[:,:-1], valid_data[:,:-1], test_dataif select_all:# feat_idx等于raw_x_train列的数量,也就是选择所有的特征feat_idx = list(range(raw_x_train.shape[1]))else:feat_idx = [0,1,2,3,4] # TODO: Select suitable feature columns.return raw_x_train[:,feat_idx], raw_x_valid[:,feat_idx], raw_x_test[:,feat_idx], y_train, y_valid
训练循环
# 定义训练器
def trainer(train_loader, valid_loader, model, config, device):# 定义损失函数 这里用的是均值方差MSELosscriterion = nn.MSELoss(reduction='mean') # Define your loss function, do not modify this.# 定义优化算法以及正则化(如何实现正则化)# 这里用的是随机梯度下降SGD,# 其中model.parameters是要优化的参数,即模型中的权重和偏置# lf是learning rate,即学习率,是一个超参数,这里通过config字典中获取# momentum动量,是另一个超参数,帮助优化器在正确的方向上收敛,并减少震荡。动量的值通常设置在0.5到0.9之间# Define your optimization algorithm. # TODO: Please check https://pytorch.org/docs/stable/optim.html to get more available algorithms.# TODO: L2 regularization (optimizer(weight decay...) or implement by your self).optimizer = torch.optim.SGD(model.parameters(), lr=config['learning_rate'], momentum=0.9) # 创建一个写入器,用于记录和可视化训练数据writer = SummaryWriter() # Writer of tensoboard.# 创建文件夹if not os.path.isdir('./models'):os.mkdir('./models') # Create directory of saving models.# 初始化训练总次数,最佳损失值,步数,早停计时器(如果在连续多个训练轮次(epochs)中,模型在验证集上的性能(如损失值或准确率)没有得到提升,那么就会停止训练。)n_epochs, best_loss, step, early_stop_count = config['n_epochs'], math.inf, 0, 0# 循环训练(核心)for epoch in range(n_epochs):# 设置模型为训练模式model.train() # Set your model to train mode.loss_record = []# 用于显示任务进度,每次迭代train_loader时,tqdm就会更新一次进度条# tranin_pbar:通过tqdm封装了数据加载器train_loader# tqdm is a package to visualize your training progress.train_pbar = tqdm(train_loader, position=0, leave=True)# 遍历train_loader中的每一项数据,x是特征,y是目标for x, y in train_pbar:# 重置梯度为0,为啥optimizer.zero_grad() # Set gradient to zero.# 将数据移动到设备中,比如CPU,比如GPUx, y = x.to(device), y.to(device) # Move your data to device. # 通过model(x)预测y的值pred = model(x) # 计算预测值和真实值的损失loss = criterion(pred, y)# 反向传播计算损失的梯度loss.backward() # Compute gradient(backpropagation).# 根据计算出的梯度更新模型的参数optimizer.step() # Update parameters.# 步数加一step += 1# 将当前的损失值添加到损失记录列表中loss_record.append(loss.detach().item())# Display current epoch number and loss on tqdm progress bar.# 在进度条上显示当前的轮次信息,使用了python的f-string格式化字符串train_pbar.set_description(f'Epoch [{epoch+1}/{n_epochs}]')# 进度条上显示当前的损失值,set_postfix()是在进度条后面加上后缀# loss.detach()这个操作是将当前的损失值从计算图中分离出来,使其不再参与梯度的计算。这样做的好处是可以节省计算资源# .item()是一个方法,它将一个标量张量转换为一个Python数值。train_pbar.set_postfix({'loss': loss.detach().item()})# 计算训练数据的平均损失mean_train_loss = sum(loss_record)/len(loss_record)# 将平均损失写入到TensorBoard中,便于后续可视化writer.add_scalar('Loss/train', mean_train_loss, step)# 设置model模式为评估模式model.eval() # Set your model to evaluation mode.# 重置损失列表loss_record = []# 遍历验证数据for x, y in valid_loader:x, y = x.to(device), y.to(device)# 不使用梯度下降,通过model()得到预测值,与实际值计算losswith torch.no_grad():pred = model(x)loss = criterion(pred, y)# 将loss存到损失列表中loss_record.append(loss.item())# 计算校验数据的平均损失 mean_valid_loss = sum(loss_record)/len(loss_record)# 打印出当前的轮次、训练损失和验证损失print(f'Epoch [{epoch+1}/{n_epochs}]: Train loss: {mean_train_loss:.4f}, Valid loss: {mean_valid_loss:.4f}')writer.add_scalar('Loss/valid', mean_valid_loss, step)# 如果当前的验证损失小于最佳损失,则保存当前模型,并重置早停计数器;否则,早停计数器加1if mean_valid_loss < best_loss:best_loss = mean_valid_losstorch.save(model.state_dict(), config['save_path']) # Save your best modelprint('Saving model with loss {:.3f}...'.format(best_loss))early_stop_count = 0else: early_stop_count += 1# if early_stop_count >= config['early_stop']::如果早停计数器的值大于或等于设定的早停值,那么停止训练if early_stop_count >= config['early_stop']:print('\nModel is not improving, so we halt the training session.')return
配置项
device = 'cuda' if torch.cuda.is_available() else 'cpu'
config = {'seed': 5201314, # Your seed number, you can pick your lucky number. :)'select_all': True, # Whether to use all features.'valid_ratio': 0.2, # validation_size = train_size * valid_ratio'n_epochs': 3000, # Number of epochs. 'batch_size': 256, 'learning_rate': 1e-5, 'early_stop': 400, # If model has not improved for this many consecutive epochs, stop training. 'save_path': './models/model.ckpt' # Your model will be saved here.# ckpt:TensorFlow中用于存储模型参数的一种文件格式
}
数据导入
# Set seed for reproducibility
# 设置在随机种子,保证每次训练的结果都是一样
same_seed(config['seed'])# train_data size: 2699 x 118 (id + 37 states + 16 features x 5 days)
# test_data size: 1078 x 117 (without last day's positive rate)
# 从文件中导入训练数据以及测试数据,然后把训练数据再划分成训练数据和验证数据
train_data, test_data = pd.read_csv('./covid.train.csv').values, pd.read_csv('./covid.test.csv').values
train_data, valid_data = train_valid_split(train_data, config['valid_ratio'], config['seed'])# Print out the data size.
print(f"""train_data size: {train_data.shape}
valid_data size: {valid_data.shape}
test_data size: {test_data.shape}""")# Select features
# 选择特征列
x_train, x_valid, x_test, y_train, y_valid = select_feat(train_data, valid_data, test_data, config['select_all'])# Print out the number of features.
print(f'number of features: {x_train.shape[1]}')# 封装数据集为自定义的dataSet
train_dataset, valid_dataset, test_dataset = COVID19Dataset(x_train, y_train), \COVID19Dataset(x_valid, y_valid), \COVID19Dataset(x_test)# Pytorch data loader loads pytorch dataset into batches.
# shuffle是否在每个训练轮次开始时打乱数据。设置为True可以帮助防止模型记住数据的顺序,从而提高模型的泛化能力# pin_memory这个参数是用来提高数据加载速度的。
# 如果设置为True,那么数据加载器会将数据放在CUDA固定内存(锁页内存)中,而不是默认的交换内存中。
# 当你使用GPU训练模型时,将数据从CPU内存移动到GPU内存的速度会更快。
# 但是,这会占用更多的RAM,因此只在你有足够内存的情况下使用这个选项
train_loader = DataLoader(train_dataset, batch_size=config['batch_size'], shuffle=True, pin_memory=True)
valid_loader = DataLoader(valid_dataset, batch_size=config['batch_size'], shuffle=True, pin_memory=True)
test_loader = DataLoader(test_dataset, batch_size=config['batch_size'], shuffle=False, pin_memory=True)
开始训练
model = My_Model(input_dim=x_train.shape[1]).to(device) # put your model and data on the same computation device.
trainer(train_loader, valid_loader, model, config, device)