机器学习Hw1--COVID-19 Cases Prediction

0 任务简介

在这里插入图片描述
根据前面三天的数据预测后面一天的新冠概率

1 代码分析

请添加图片描述

Def and Class

import

# Numerical Operations
import math
import numpy as np

# Reading/Writing Data
import pandas as pd
import os
import csv

# For Progress Bar  Tqdm 是一个快速,可扩展的Python进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器 tqdm(iterator)。
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
  • numpy
  • csv
  • torch.nn
  • torch.utils.tensorboard

seed

def same_seed(seed): 
       # A bool that, if True, causes cuDNN to only use deterministic convolution algorithms.
    # cudnn: 是经GPU加速的深度神经网络基元库。cuDNN可大幅优化标准例程(例如用于前向传播和反向传播的卷积层、池化层、归一化层和激活层)的实施。
    torch.backends.cudnn.deterministic = True
    # A bool that, if True, causes cuDNN to benchmark multiple convolution algorithms and select the fastest.
    torch.backends.cudnn.benchmark = False
    # 用于生成指定的随机数
    np.random.seed(seed)
    # Sets the seed for generating random numbers. cpu生成随机数
    torch.manual_seed(seed)
    if torch.cuda.is_available():
      # Sets the seed for generating random numbers for the current GPU. Gpu生成随机数
      # It’s safe to call this function if CUDA is not available; in that case, it is silently ignored.cuda不可用就不会被调用
        torch.cuda.manual_seed_all(seed)
        

主要作用:可重现一样的结果
set.seed()作用是设定生成随机数的种子,目的是为了让结果具有重复性,重现结果。
在神经网络中,参数默认是进行随机初始化的。如果不设置的话每次训练时的初始化都是随机的,导致结果不确定。如果设置初始化,则每次初始化都是固定的。

train_valid_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
    # Randomly split a dataset into non-overlapping new datasets of given lengths. 
    # Optionally fix the generator for reproducible results
    # 随机划分
    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)

predict

模型训练出来后调用这个模块预测结果

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(): # with用法?                  
            pred = model(x)                     
            preds.append(pred.detach().cpu())   #我在想这里可不可以用pred.index
 
    preds = torch.cat(preds, dim=0).numpy()  
    return preds
  • detach()

作用:阻断反向传播的。
返回值:Tensor,且经过detach()方法后,变量仍然在GPU上。

 output = output.detach().cpu() # 移至cpu 返回值是cpu上的Tensor

要注意,Tensor变量使用后会生成计算图,为计算反向传播做准备,但是会占用资源

此时output仍然在显存中,而内存操作可能会找不到该变量,也就是说,show(output)是没办法进行操作的。那么cpu()出现了。

 output = output.detach().cpu() # 移至cpu 返回值是cpu上的Tensor

后续,则可以对该Tensor数据进行一系列操作,其中包括numpy(),该方法主要用于将cpu上的tensor转为numpy数据。

	 output = output.detach().cpu().numpy()  # 返回值为numpy.array()

detach

1.2torch.cat()

COVID19Dataset

生成数据集

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)

My_Model

class Model(torch.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
        return  x

select_feat

选择特征。。数据集中几十个元素中,选出一些影响较为大的。

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

trainer

def trainer(train_loader, valid_loader, model, config, device):

    criterion = nn.MSELoss(reduction='mean') # Define your loss function, do not modify this.损失函数MSE

    # 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).
    #优化算法,lr指学习率,momentum=冲量?						
    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

main

# 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('./Hw1/covid.train_new.csv').values, pd.read_csv('./Hw1/covid.test_un.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)

#start

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)

在这里插入图片描述

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

2 总结

  • tensorboard不会用
  • 特征选择没做
  • 测试模型,只有models怎么测,以及误差比较
%reload_ext tensorboard
%tensorboard --logdir=./runs/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值