PyTorch处理多维特征输入

PyTorch处理多维特征输入

使用sklearn包中的糖尿病数据集
路径为:conda\\lib\\site-packages\\sklearn\\datasets\\data

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
# -*- coding: UTF-8 -*-
import torch.nn as nn
import torch.optim as optim
import torch
import numpy as np
import matplotlib.pyplot as plt

# gz压缩包的文件名一样,可以使用loadtxt把数据读出来
# delimiter=',',使用逗号作为分隔符
# dtype=np.float32,数据类型为32位的浮点型
xy = np.loadtxt('./diabetes_data/diabetes.csv.gz',delimiter=',',dtype=np.float32)

#
x_data = torch.from_numpy(xy[:,:-1]) # 所有行,除去最后一列
y_data = torch.from_numpy(xy[:,[-1]]) #所有行,最后一列转为矩阵

class Model(nn.Module):
def __init__(self):
super(Model,self).__init__()
self.linear1 = nn.Linear(8,16)
self.linear2 = nn.Linear(16,32)
self.linear3 = nn.Linear(32,64)
self.linear4 = nn.Linear(64,32)
self.linear5 = nn.Linear(32,1)
self.sigmoid = nn.Sigmoid()

def forward(self,x):
x = self.sigmoid(self.linear1(x))
x = self.sigmoid(self.linear2(x))
x = self.sigmoid(self.linear3(x))
x = self.sigmoid(self.linear4(x))
x = self.sigmoid(self.linear5(x))
return x

model = Model()

loss_function = nn.BCELoss(reduction='mean')
optimizer = optim.Adam(model.parameters(),lr=0.055)

epoch_list = []
loss_list = []

for epoch in range(1000):
y_pred = model(x_data)
loss = loss_function(y_pred,y_data)

epoch_list.append(epoch)
loss_list.append(loss.data.item())

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

plt.plot(epoch_list, loss_list)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()

Donate comment here