李宏毅机器学习Homework1(代码简洁版)

李宏毅机器学习Homework1

  • 题意大概是(我具体没怎么听,觉得有问题的小伙伴可以提醒我一句),给你前四天的数据,根据第5天的身体状况预测第五天的test_positive,具体数据b站有,懒得放了
  • 因为电脑没有GPU所以我懒得管那些GPU的设置了,然后代码主要是训练模块,测试模块实际上就是把网络设置成推理模式,然后自己跑,很简单的我就不写了
  • 这个问题单纯是练手的,我也没看老师的代码是怎么做的,反正训练效果我感觉差不多就行了,就不多说废话,调整超参数那些自己可以尝试搞一搞
  • 最后大家感兴趣的话可以关注我的个人公众号右转的第二排架子,里面(将)有相关内容
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import csv
import numpy as np
import matplotlib.pyplot as plt

train_path = 'covid.train.csv'
test_path = 'covid.test.csv'

class Net(nn.Module):
    def __init__(self, input_dim, output_dim):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(input_dim, 100)
        self.fc2 = nn.Linear(100, 50)
        self.fc3 = nn.Linear(50, 30)
        self.fc4 = nn.Linear(30, output_dim)

    def forward(self, state):
        output = F.relu((self.fc1(state)))
        output = F.relu((self.fc2(output)))
        output = F.relu((self.fc3(output)))
        output = self.fc4(output)
        
        return output

class Covid19_Dataset:
    def __init__(self, train_path, test_path):
        self.train_path = train_path
        self.test_path = test_path
        _, self.train_data = self.load_data(train_path)
        _, self.test_data = self.load_data(test_path) 
        
    '''
    *******************************************************************
        id       : line 1
        location : line 2 - 38
        day1     : line 39 - 54
        day2     : line 55 - 70
        day3     : line 71 - 86
        day4     : line 87 - 102
        
    if train_data:
        day5     : line 103 - 118
        
    if test_data:  id + 116
        day5     : line 103 - 117 (need to predict 'tested_positve' according to relevant parameters)
    *******************************************************************
    '''

    def load_data(self, filepath):
        with open(filepath, 'r') as f:
            reader = csv.reader(f)
            index = next(reader)
            data = np.array([*reader]).astype(np.float64)
        
        return index, data

    def sample_data(self, Batch_size, data):
        index = np.random.choice(len(data), size = Batch_size, replace = False) #不放回抽样
        sample_data = []
        for sample_index in index:
            sample_data.append(data[sample_index])
        return np.array(sample_data)
    
if __name__ == '__main__':
    
    Batch_size = 16
    input_dim = 116
    output_dim = 1
    learning_rate = 0.001
    net = Net(input_dim, output_dim)
    dataset = Covid19_Dataset(train_path, test_path)

    criterion = nn.MSELoss(reduction = 'mean')
    optimizer = optim.Adam(net.parameters(), lr = learning_rate)
    
    Episode = np.arange(1, 1000)
    Episode_loss = []
    
    for epoch in Episode:
        sample_train_data = dataset.sample_data(Batch_size, dataset.train_data)

        sample_input_data = torch.FloatTensor(sample_train_data[:, 1:117])
        sample_label_data = torch.FloatTensor(sample_train_data[:, -1]).unsqueeze(1)
        
        net.eval()
        predict_data = net(sample_input_data)

        net.train()
        loss = criterion(predict_data, sample_label_data)
        Episode_loss.append(loss.item())
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    
    Episode_loss = np.array(Episode_loss)
    plt.plot(Episode, Episode_loss)
    plt.show()


你可能感兴趣的:(人工智能,深度学习,人工智能)