糖尿病的预测(pytorch)

import numpy as np
import torch

# 糖尿病预测研判
# 1. 处理数据
xy = np.loadtxt('diabetes.csv.gz', delimiter=',', dtype=np.float32)
x_data = torch.from_numpy(xy[:, :-1])
y_data = torch.from_numpy(xy[:, [-1]])

# 2. 建立模型
# 2. 设计模型 继承自torch.nn.Module
class Model(torch.nn.Module):
    def __init__(self):
        super(Model, 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):
        """预测结果 计算loss"""
        x = self.sigmoid(self.linear1(x))
        x = self.sigmoid(self.linear2(x))
        x = self.sigmoid(self.linear3(x))
        return x

model = Model()

# 3.0
# 损失函数
criterion = torch.nn.BCELoss(size_average=False)
# 优化器
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

# 4. 训练周期
for epoch in range(1000000):
    # 调用forward函数
    y_pred = model(x_data)
    # 计算损失 loss为一个标量
    loss = criterion(y_pred, y_data)
    # print(epoch, loss)
    # 清空本次计算数据 梯度清零
    optimizer.zero_grad()
    # 反向传播
    loss.backward()
    # 更新参数
    optimizer.step()
    print(epoch, loss.item())

 

你可能感兴趣的:(深度学习,机器学习,Python开发)