《PyTorch深度学习实践》第八课导入数据

b站刘二视频,地址:

https://www.bilibili.com/video/BV1Y7411d7Ys?p=9&vd_source=79d752a233297190ff0b01ca81ccd878

代码(课中作业) 

还是上节课的糖尿病的二元分类问题,四步法构造

import torch
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset
from torch.utils.data import DataLoader

#-------------------------------------------step1  prepare data----------------------------------------
class Data(Dataset): #构造自己的类,继承自Dataset类
    def __init__(self, filepath):
        xy = np.loadtxt(filepath, delimiter=',', dtype=np.float32)
                        #文件路径   数据中的分隔符   数据类型
        self.len = xy.shape[0] #返回几行几列(矩阵)
        self.x_data = torch.from_numpy(xy[:, :-1])#取每一行,取到最后一列
        self.y_data = torch.from_numpy(xy[:, [-1]])#取每一行,取最后一列

    def __getitem__(self, item): #获取某一行元素
        return self.x_data[item], self.y_data[item]

    def __len__(self):
        return self.len

dataset = Data('diabetes.csv')
dataloader = DataLoader(dataset=dataset, batch_size=32, shuffle=True)

#------------------------------------------setp2 design model--------------------------------------------

class Modle(torch.nn.Module):
    def __init__(self):
        super(Modle, self).__init__()
        self.linear1 = torch.nn.Linear(8, 6)
        self.linear2 = torch.nn.Linear(6, 4)
        self.linear3 = torch.nn.Linear(4, 1)
        self.sigmoid = torch.nn.Sigmoid()

    def forward(self, x):
        x = self.sigmoid(self.linear1(x))
        x = self.sigmoid(self.linear2(x))
        x = self.sigmoid(self.linear3(x))
        return x

model = Modle()

#---------------------------------------step3    constuct loss and optimizer-----------------------------

criteration = torch.nn.BCELoss(reduction='mean')#mean求均值
optimizer = torch.optim.SGD(model.parameters(), lr=0.0001) #要更新的是model中的参数, 学习率

#---------------------------------------step4 traning cycle------------------------------------------

if __name__ == '__main__': #要写这个

    loss_lst = []

    for epoch in range(1000):#外层epoch是所有数据集都遍历过的一次训练
        sum = 0#
        for i, data in enumerate(dataloader, 0):#一次是一个batch,从整个数据集中的一部分
            inputs, lables = data#x y
            y_pred = model(inputs)
            loss = criteration(y_pred, lables)
            sum += loss.item()

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

        loss_lst.append(sum / dataloader.batch_size)
    #可视化
    num_lst = [i for i in range(len(loss_lst))]
    plt.plot(num_lst, loss_lst)
    plt.xlabel("epoch")
    plt.ylabel("loss")
    plt.show()



运行结果

《PyTorch深度学习实践》第八课导入数据_第1张图片

MINIST数据导入

 

 

你可能感兴趣的:(PyTorch刘二,深度学习,pytorch,python)