pytorch使用Dataset分批次处理数据

学习b站刘二大人视频所写
视频传送门

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


# prepare dataset
class DiabetesDataset(Dataset):
    def __init__(self, filepath):
        xy = np.loadtxt(filepath, delimiter=' ', dtype=np.float32)
        self.len = xy.shape[0]  # shape(多少行,多少列)
        self.x_data = torch.from_numpy(xy[:, :-1])
        self.y_data = torch.from_numpy(xy[:, [-1]])

    def __getitem__(self, index):
        return self.x_data[index], self.y_data[index]

    def __len__(self):
        return self.len


data_set = DiabetesDataset('000.txt')
train_loader = DataLoader(dataset=data_set, batch_size=32, shuffle=True)
# data_set 要加载的数据
# batch_size 表示每个mini-bach含样本的个数
# shuffle=True 表示要打乱样本顺序
# num_workers 多线程


# design model using class
class Model(torch.nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear1 = torch.nn.Linear(9, 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 = Model()

# construct loss and optimizer
criterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
loss_sum = []
# training cycle forward, backward, update

for epoch in range(100):
    for i, (inputs, labels) in enumerate(train_loader, 0):  # train_loader 是先shuffle后mini_batch
        # dataloader将输入与标签放在一个元组里
        y_pred = model(inputs)
        loss = criterion(y_pred, labels)
        print(epoch, i, loss.item())
        # 梯度清零,反向传播
        optimizer.zero_grad()
        loss.backward()
        # 更新
        optimizer.step()
        if i == 13:
            loss_sum.append(loss.item())


x = range(100)
y = loss_sum
plt.plot(x, y)
plt.xlabel('Epoch')
plt.ylabel('loss')
plt.grid()  # 生成网格
plt.show()

取每次训练的最后一个Loss作图

pytorch使用Dataset分批次处理数据_第1张图片
取每次epoch的平均loss画图

for epoch in range(100):
    l_loss = 0
    for i, (inputs, labels) in enumerate(train_loader, 0):  # train_loader 是先shuffle后mini_batch
        # dataloader将输入与标签放在一个元组里
        y_pred = model(inputs)
        loss = criterion(y_pred, labels)
        print(epoch, i, loss.item())
        # 梯度清零,反向传播
        optimizer.zero_grad()
        loss.backward()
        # 更新
        optimizer.step()
        l_loss += loss.item()

    l_loss = l_loss / (i + 1)
    loss_sum.append(l_loss)

pytorch使用Dataset分批次处理数据_第2张图片

你可能感兴趣的:(python及AI,神经网络,深度学习,python,pytorch,dataset)