糖尿病数据集训练pytorch

import torch
import numpy as np
from matplotlib import pyplot as plt
#加载数据集
xy = np.loadtxt('diabetes.csv',delimiter=',',dtype=np.float32)
x_data = torch.from_numpy(xy[:,:-1])
y_data = torch.from_numpy(xy[:,[-1]])
#print(x_data)
#建立模型
class MyModel(torch.nn.Module):
    def __init__(self):
        super(MyModel,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):
        x = self.sigmoid(self.linear1(x))
        x = self.sigmoid(self.linear2(x))
        x = self.sigmoid(self.linear3(x))
        return x
#实例化
model = MyModel()
#loss和优化器
criterion = torch.nn.BCELoss(size_average = True)
optimzer = torch.optim.SGD(model.parameters(),lr = 0.1)
#训练
a_data = []
b_data = []
for epoch in range(200):
    #forward
    a_data.append(epoch+1)
    y_pred = model(x_data)
    loss = criterion(y_pred,y_data)
    b_data.append(loss.item())
    print(epoch+1,loss.item())
    optimzer.zero_grad()
    #backward
    loss.backward()
    #updata
    optimzer.step()
plt.plot(a_data, b_data, ls="-.", lw=2, c="c", label="plot figure")
plt.xlabel('num of train')
plt.ylabel('loss')
plt.grid()#网格
plt.show()

==主要注意这里loss的求法,求交叉熵的方式

结果:

猜你喜欢

转载自blog.csdn.net/luoshiyong123/article/details/107808332