《PyTorch深度学习实践》处理多维特征输入

课程请见 《PyTorch深度学习实践》
数据集见链接:https://pan.baidu.com/s/1koPyBGQ7ORaH1OHGH9IO8Q
提取码:jph5

# PyTorch
import torch
from torch import nn
from torch import optim
from torch.utils import data
# NumPy
import numpy as np


class DiabetesDataset(data.Dataset):
    def __init__(self, path):
        self.cor = np.loadtxt(path, delimiter=',', dtype=np.float32)
        self.len = self.cor.shape[0]
        self.x_data = torch.from_numpy(self.cor[:, :-1])
        self.y_data = torch.from_numpy(self.cor[:, -1]).reshape(-1, 1)

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

    def __len__(self):
        return self.len


class Model(nn.Module):
    def __init__(self, input_dim, out_dim=1):
        super(Model, self).__init__()
        self.linear1 = nn.Linear(input_dim, 6)
        self.linear2 = nn.Linear(6, 4)
        self.linear3 = nn.Linear(4, 1)
        self.activate = nn.ReLU()

    def forward(self, x):
        _y1 = self.activate(self.linear1(x))
        _y2 = self.activate(self.linear2(_y1))
        _y3 = torch.sigmoid(self.linear3(_y2))
        return _y3


batch_size = 62
train_data = DiabetesDataset('../data/diabetes.csv')
train_iter = data.DataLoader(
    dataset=train_data,
    batch_size=batch_size,
    shuffle=True,
    num_workers=1
)

net = Model(8)
criterion = nn.BCELoss()
optimizer = optim.SGD(net.parameters(), lr=0.03)
num_epochs = 100
num_iter = len(train_data) // batch_size + 1 \
    if len(train_iter) % batch_size else len(train_data) // batch_size

if __name__ == '__main__':
    for epoch in range(num_epochs):
        epoch_loss = 0
        for x, y in train_iter:
            _y = net(x)
            loss = criterion(_y, y)
            epoch_loss += loss.item()
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
        print('第{}轮,loss为{:.8f}'.format(epoch + 1, epoch_loss / num_iter))


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值