目录
数据集
导包
辅助函数
设定种子
划分数据集
模型
特征选择
训练函数
配置参数
Dataloader
开始训练
预测
预测函数
输出结果
解答
训练函数
模型
特征选择
超参数设置
训练集中给出美国某些州五天COVID-19的感染人数(及相关特征数据),测试集中给出前四天的相关数据,预测第五天的感染人数。 下载地址:ML2022Spring-hw1 | Kaggle
特征包括:
● States (37, 独热编码)
● COVID-like illness (4)
○ cli、ili …
● Behavior Indicators (8)
○ wearing_mask、travel_outside_state …
● Mental Health Indicators (3)
○ anxious、depressed …
● Tested Positive Cases (1)
○ tested_positive (this is what we want to predict)
训练集有2699行, 118列 (id + 37 states + 16 features x 5 days)
测试集有1078,117列 (without last day's positive rate)
# Numerical Operations
import math
import numpy as np
from sklearn.model_selection import train_test_split
# Reading/Writing Data
import pandas as pd
import os
import csv
# For Progress Bar
from tqdm import tqdm
from d2l import torch as d2l
# Pytorch
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader, random_split, TensorDataset
# For plotting learning curve
from torch.utils.tensorboard import SummaryWriter
我的理解是,模型初始化和验证集划分都要用到seed,这里固定下来
def same_seed(seed):
'''Fixes random number generator seeds for reproducibility.'''
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
可以使用random_split函数
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, 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)
也可以采取train_test_split函数
def train_valid_split(data_set, valid_ratio, seed):
'''Split provided training data into training set and validation set'''
train_set, valid_set = train_test_split(data_set, test_size=valid_ratio, random_state=seed)
return np.array(train_set), np.array(valid_set)
整个作业最重要的就是模型和特征选择,还有超参数设置。这里放原代码
class My_Model(nn.Module):
def __init__(self, input_dim):
super(My_Model, self).__init__()
# TODO: modify model's structure, be aware of dimensions.
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 = self.layers(x)
x = x.squeeze(1) # (B, 1) -> (B)
return x
对原代码进行了改动,因为使用了TensorDataset,它的自变量应该是tensor,所以要把train_data, valid_data, test_data变为tensor格式
def select_feat(train_data, valid_data, test_data, select_all=True):
'''Selects useful features to perform regression'''
train_data = torch.FloatTensor(train_data)
valid_data = torch.FloatTensor(valid_data)
test_data = torch.FloatTensor(test_data)
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_data
if select_all:
feat_idx = list(range(raw_x_train.shape[1]))
else:
feat_idx = [0,1,2,3] # 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
以下是原代码给出的模板,使用了tqdm来呈现训练过程
def trainer(train_loader, valid_loader, model, config, device):
criterion = nn.MSELoss(reduction='mean') # Define your loss function, do not modify this.
# 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.
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 = []
# tqdm is a package to visualize your training progress.
train_pbar = tqdm(train_loader, position=0, leave=True)
for x, y in train_pbar:
optimizer.zero_grad() # Set gradient to zero.
x, y = x.to(device), y.to(device) # Move your data to device.
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.
train_pbar.set_description(f'Epoch [{epoch+1}/{n_epochs}]')
train_pbar.set_postfix({'loss': loss.detach().item()})
mean_train_loss = sum(loss_record)/len(loss_record)
writer.add_scalar('Loss/train', mean_train_loss, step)
model.eval() # Set your model to evaluation mode.
loss_record = []
for x, y in valid_loader:
x, y = x.to(device), y.to(device)
with torch.no_grad():
pred = model(x)
loss = criterion(pred, y)
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)
if mean_valid_loss < best_loss:
best_loss = mean_valid_loss
torch.save(model.state_dict(), config['save_path']) # Save your best model
print('Saving model with loss {:.3f}...'.format(best_loss))
early_stop_count = 0
else:
early_stop_count += 1
if early_stop_count >= config['early_stop']:
print('\nModel is not improving, so we halt the training session.')
return
config
contains hyper-parameters for training and the path to save your model.
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.
}
使用TensorDataset来包装数据集,而不是像原代码自定义了一个
# 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, False)
# Print out the number of features.
print(f'number of features: {x_train.shape[1]}')
train_dataset, valid_dataset, test_dataset = TensorDataset(x_train, y_train), \
TensorDataset(x_valid, y_valid), \
TensorDataset(x_test)
# Pytorch data loader loads pytorch dataset into batches.
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)
使用nn.DataParallel函数进行并行计算。我在kaggle上使用GPU T4, 选择使用并行计算,能看到两块GPU都被占用了,但是计算速度比不使用并行计算还要慢一半,奇怪了。有没有大神解答一下
devices = d2l.try_all_gpus()
model = My_Model(input_dim=x_train.shape[1]) # put your model and data on the same computation device.
model = nn.DataParallel(model, device_ids = devices).to(devices[0])
trainer(train_loader, valid_loader, model, config)
def predict(test_loader, model, devices):
model.eval() # Set your model to evaluation mode.
preds = []
for x in tqdm(test_loader):
x = x[0].to(devices[0])
with torch.no_grad():
pred = model(x)
preds.append(pred.detach().cpu())
preds = torch.cat(preds, dim=0).numpy()
return preds
def save_pred(preds, file):
''' Save predictions to specified file '''
with open(file, 'w') as f:
f.write('id,tested_positive' + '\n')
for i, p in enumerate(preds):
f.write(str(i) + ',' + str(p) + '\n')
model = My_Model(input_dim=x_train.shape[1]).to(devices[0])
model = nn.DataParallel(model, device_ids = devices).to(devices[0])
model.load_state_dict(torch.load(config['save_path']))
preds = predict(test_loader, model, devices)
save_pred(preds, 'pred.csv')
使用了《动手学深度学习》这本书中的d2l工具包,在训练过程画出loss。注意这里使用了adam函数,在optimizer中加入L2正则,并且使用CosineAnnealingWarmRestarts函数调整学习率。
def trainer(train_loader, valid_loader, model, config, devices):
criterion = nn.MSELoss(reduction='mean') # Define your loss function, do not modify this.
# 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.Adam(model.parameters(), lr=config['learning_rate'], weight_decay=config['weight_decay'])
scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer,
T_0=2, T_mult=2, eta_min=config['learning_rate']/50)
writer = SummaryWriter() # Writer of tensoboard.
if not os.path.isdir('./models'):
os.mkdir('./models') # Create directory of saving models.
n_epochs, best_loss, step, early_stop_count = config['n_epochs'], math.inf, 0, 0
legend = ['train loss']
if valid_loader is not None:
legend.append('valid loss')
animator = d2l.Animator(xlabel='epoch', xlim=[1, n_epochs], ylim=[0.5, 2.5], legend=legend)
for epoch in range(n_epochs):
model.train() # Set your model to train mode.
loss_record = []
for x, y in train_loader:
optimizer.zero_grad() # Set gradient to zero.
x, y = x.to(devices[0]), y.to(devices[0]) # Move your data to device.
pred = model(x)
loss = criterion(pred, y)
loss.backward() # Compute gradient(backpropagation).
optimizer.step() # Update parameters.
step += 1
loss_record.append(loss.detach().item())
scheduler.step()
mean_train_loss = sum(loss_record)/len(loss_record)
writer.add_scalar('Loss/train', mean_train_loss, step)
animator.add(epoch + 1, (mean_train_loss, None))
if valid_loader is not None:
model.eval() # Set your model to evaluation mode.
loss_record = []
for x, y in valid_loader:
x, y = x.to(devices[0]), y.to(devices[0])
with torch.no_grad():
pred = model(x)
loss = criterion(pred, y)
loss_record.append(loss.item())
mean_valid_loss = sum(loss_record)/len(loss_record)
writer.add_scalar('Loss/valid', mean_valid_loss, step)
animator.add(epoch +1, (None, mean_valid_loss))
if mean_valid_loss < best_loss:
best_loss = mean_valid_loss
torch.save(model.state_dict(), config['save_path']) # Save your best model
# print('Saving model with loss {:.3f}...'.format(best_loss))
early_stop_count = 0
else:
early_stop_count += 1
if early_stop_count >= config['early_stop']:
# print('\nModel is not improving, so we halt the training session.')
return
加深了一层
class My_Model(nn.Module):
def __init__(self, input_dim):
super(My_Model, self).__init__()
# TODO: modify model's structure, be aware of dimensions.
self.layers = nn.Sequential(
nn.Linear(input_dim, 16),
nn.ReLU(),
nn.Linear(16, 8),
nn.ReLU(),
nn.Linear(8, 4),
nn.ReLU(),
nn.Linear(4, 1)
)
def forward(self, x):
x = self.layers(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'''
train_data = torch.FloatTensor(train_data)
valid_data = torch.FloatTensor(valid_data)
test_data = torch.FloatTensor(test_data)
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_data
if select_all:
feat_idx = list(range(raw_x_train.shape[1]))
else:
feat_idx = [53, 69, 85, 101] # 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
学习率非常重要,大体试几个数即可确定范围:在有的学习率下,迭代了200步,loss还是好几十;在合适的学习率下,迭代了不到50步,loss就降到了个位数。后者是想要的
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-3,
'weight_decay': 1e-4,
'early_stop': 900, # If model has not improved for this many consecutive epochs, stop training.
'save_path': './models/model.ckpt', # Your model will be saved here.
}
通过Strong Baseline
其实步调整模型层数也行,结果如下图,几乎一模一样
模型设置和特征选择可以更加复杂,结果也会更好,可以参考:
李宏毅2022机器学习HW2解析_机器学习手艺人的博客-CSDN博客_李宏毅机器学习作业2