使用PyTorch预测糖尿病(B站刘二大大练习题)

数据集: https://geoer666-1257264766.cos.ap-beijing.myqcloud.com/20220814205751.png

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
解决糖尿病预测的问题

"""
import torch
import numpy as np


# 1.读取数据
data = np.loadtxt("./data/diabetes.csv.gz", delimiter=",", dtype=np.float32)
x_data = torch.from_numpy(data[:-1, :-1])  # x不取最后一列
y_data = torch.from_numpy(data[:-1, [-1]])  # y取所有行和最后一列, [-1]代表是矩阵


# 2.设计模型
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()
        self.active = torch.nn.ReLU()

    def forward(self, x):
        x = self.active(self.linear1(x))  # o1
        x = self.active(self.linear2(x))  # o2
        x = self.sigmoid(self.linear3(x))  # y heat
        return x


model = Model()

# 3.构造损失和优化器
criterion = torch.nn.BCELoss(size_average=True)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)


# 4.训练
for epoch in range(1000):
    # 这里forward 并非mini-batch的设计,只是mini-batch的风格
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    print(epoch, loss.item())

    # backward
    optimizer.zero_grad()
    loss.backward()

    # update
    optimizer.step()

# 测试集
test_data = torch.from_numpy(data[[-1], :-1])
pred_test = torch.from_numpy(data[[-1], [-1]])

print("test_pred = ", model(test_data).item())
print("infact_pred = ", pred_test.item())
0%