7_dataset_loader_logistics

import torch
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import DataLoader, Dataset


class DiabetesDataset(Dataset):
    def __init__(self):
        super(DiabetesDataset, self).__init__()
        xy = np.loadtxt('.//data//diabetes.csv.gz', delimiter=',', dtype=np.float32)
        self.len = xy.shape[0]
        self.x_data = torch.from_numpy(xy[:, 0: -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


class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.l1 = nn.Linear(8, 6)
        self.l2 = nn.Linear(6, 4)
        self.l3 = nn.Linear(4, 1)

        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        out1 = self.sigmoid(self.l1(x))
        out2 = self.sigmoid(self.l2(out1))
        y_pred = self.sigmoid(self.l3(out2))
        return y_pred

    def run(self):
        model = Model()
        criterion = nn.BCELoss(reduction='sum')
        optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

        for epoch in range(2):
            for i, data in enumerate(train_loader, 0):
                inputs, labels = data
                inputs, labels = Variable(inputs), Variable(labels)
                y_pred = model(inputs)
                loss = criterion(y_pred, labels)
                print(epoch, loss.item())

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


if __name__ == "__main__":
    print("Life is short, You need Python!")
    dataset = DiabetesDataset()
    train_loader = DataLoader(dataset=dataset, batch_size=32, shuffle=True, num_workers=2)
    m = Model()
    m.run()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值