李宏毅深度学习课程Spring2022作业1

文章目录

  • 目标
  • 任务描述
  • 数据
  • 评价标准
  • Kaggle -Submission
  • 作业 simple baseline:
    • 1) Download data
    • 2) Import packages
    • 3)Some Utility Function
    • 4)Dataset
    • Neural Network Model
    • Feature Selection (划分训练集、测试集、验证集的x、y)
    • Training Loop
    • Configurations
    • Dataloader
    • Start training
    • Plot learning curves with tensorboard
    • Testing
  • 细节知识点
    • pytorch中model eval和torch no grad()的区别
    • tqdm
    • squeeze()
  • 参考资料

目标

  • 使用DNN解决一个回归问题
  • 理解DNN的基本训练技巧,比如超参数调优、特征选取、睁着
  • 熟悉Pytorch

任务描述

  • COVID-19 病例预测
    李宏毅深度学习课程Spring2022作业1_第1张图片
  • 基于调查数据预测测试阳性概率。

数据

Survey: symptoms, COVID-19 testing, social distancing, mental health, demographics,
economic effects, …

  • States (37, encoded to one-hot vectors)
  • 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)

Trian.csv中的部分数据:

在这里插入图片描述

评价标准

M S E = 1 / N ∗ s u m i = 0 N ( y i − y h a t i ) 2 MSE=1/N*sum_{i=0}^N{(y_i -yhat_i)^2} MSE=1/Nsumi=0N(yiyhati)2

Kaggle -Submission

kaggle 地址: kaggle地址

作业 simple baseline:

1) Download data

数据集可从kaggle 上下载:covid-19数据集

2) Import packages

# 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

关于tensorboard 与pytorch 的简单应用:tensorboard
tensorboard: 可视化工具

3)Some Utility Function

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)

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)

def predict(test_loader, model, device):
    model.eval() # Set your model to evaluation mode. 告诉网络,这个阶段是用来测试的,于是模型的参数在该阶段不进行更新
    preds = []
    for x in tqdm(test_loader):
        x = x.to(device)                        
        with torch.no_grad():                   
            pred = model(x)                     
            preds.append(pred.detach().cpu())   
    preds = torch.cat(preds, dim=0).numpy()  
    return preds

4)Dataset

class COVID19Dataset(Dataset):
    '''
    x: Features.
    y: Targets, if none, do prediction.
    '''
    def __init__(self, x, y=None):  ## 构造函数
        if y is None:
            self.y = y
        else:
            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)

Neural Network Model

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

Feature Selection (划分训练集、测试集、验证集的x、y)

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_data

    if select_all:
        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

Training Loop

设置损失函数、优化函数

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

Configurations

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.
}

Dataloader

Read data from files and set up training, validation, and testing sets. You do not need to modify this part.

# 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]}')

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.
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)

train_data size: (2160, 118)
valid_data size: (539, 118)
test_data size: (1078, 117)
number of features: 117

Start training

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)

李宏毅深度学习课程Spring2022作业1_第2张图片
运行结束后,在路径下多了 model 文件夹和 runs 文件夹
在这里插入图片描述

Plot learning curves with tensorboard

tensorboard is a tool that allows you to visualize your training progress.

If this block does not display your learning curve, please wait for few minutes, and re-run this block. It might take some time to load your logging information.

%reload_ext tensorboard
%tensorboard --logdir=./runs/

李宏毅深度学习课程Spring2022作业1_第3张图片

Testing

def save_pred(preds, file):
    ''' Save predictions to specified file '''
    with open(file, 'w') as fp:
        writer = csv.writer(fp)
        writer.writerow(['id', 'tested_positive'])
        for i, p in enumerate(preds):
            writer.writerow([i, p])

model = My_Model(input_dim=x_train.shape[1]).to(device)
model.load_state_dict(torch.load(config['save_path']))
preds = predict(test_loader, model, device) 
save_pred(preds, 'pred.csv')         

在本次作业中,并没有基于前5天数据预测第五天的结果,而是基于当天的特征数据进行预测的。

细节知识点

pytorch中model eval和torch no grad()的区别

  • 在PyTorch中进行validation时,会使用model.eval()切换到测试模式,在该模式下,主要用于通知dropout层和batchnorm层在train和val模式间切换

  • 在train模式下,dropout网络层会按照设定的参数p设置保留激活单元的概率(保留概率=p); batchnorm层会继续计算数据的mean和var等参数并更新。

  • 在val模式下,dropout层会让所有的激活单元都通过,而batchnorm层会停止计算和更新mean和var,直接使用在训练阶段已经学出的mean和var值。该模式不会影响各层的gradient计算行为,即gradient计算和存储与training模式一样,只是不进行反传(backprobagation)

  • 而with torch.no_grad()则主要是用于停止autograd模块的工作,以起到加速和节省显存的作用,具体行为就是停止gradient计算,从而节省了GPU算力和显存,但是并不会影响dropout和batchnorm层的行为。

  • 一般情况下,我们训练过程如下
    1、拿到数据后进行训练,在训练过程中,使用model.train():告诉我们的网络,这个阶段是用来训练的,可以更新参数。
    2、训练完成后进行预测,在预测过程中,使用model.eval() : 告诉我们的网络,这个阶段是用来测试的,于是模型的参数在该阶段不进行更新。

  • 为什么在eval()阶段会使用with torch.no_grad()?
    在eval阶段了,即使不更新,但是在模型中所使用的dropout或者batch norm也就失效了,直接都会进行预测,而使用no_grad则设置让梯度Autograd设置为False(因为在训练中我们默认是True),这样保证了反向过程为纯粹的测试,而不变参数。

tqdm

Tqdm 是一个快速,可扩展的Python进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器 tqdm(iterator)。
用法:tqdm(iterator)
使用方法一: 传入可迭代对象

import time
from tqdm import *
for i in tqdm(range(1000)):
    time.sleep(.01)    #进度条每0.1s前进一次,总时间为1000*0.1=100s

100%|██████████████████████████████████████████████████████████████████████████████| 1000/1000 [00:10<00:00, 93.97it/s]

使用方法二: trange
trange(i) 是 tqdm(range(i)) 的简单写法

from tqdm import trange
for i in trange(100):
    #do something
    pass

100%|█████████████████████████████████████████████████████████████████████████████| 100/100 [00:00<00:00, 99344.01it/s]

使用方法三: 可以为进度条设置描述
在 for 循环外部初始化 tqdm,可以打印其他信息:

import time
from tqdm import tqdm
 
pbar = tqdm(["a", "b", "c", "d"])
for char in pbar:
    # 设置描述
    pbar.set_description("Processing %s" % char)
    time.sleep(1)

Processing d: 100%|██████████████████████████████████████████████████████████████████

squeeze()

squeeze unsqueeze的用法

参考资料

  1. pytorch model.eval
  2. tqdm

你可能感兴趣的:(深度学习,机器学习)