Pytorch学习(6):多维输入

import torch
import numpy as np


#数据读入
xy = np.loadtxt('diabetes.csv.gz',delimiter=',',dtype=np.float32)     #delimiter 指的是分隔符的意思
x_data = torch.from_numpy(xy[:,:-1])     #x_data是前8列
y_data = torch.from_numpy(xy[:,[-1]])    # y_data是最后1列


class Model(torch.nn.Module):
    def __init__(self):
        super(Model,self).__init__()
        #self.linear = torch.nn.Linear(8,1)     #直接8维输入,1维输出的二分类模型 对应的w为8*1的向量。
        self.linear1 = torch.nn.Linear(8,6)
        self.linear2 = torch.nn.Linear(6,4)
        self.linear3 = torch.nn.Linear(4,1)    #从8->4->1维
        
        self.sigmoid = torch.nn.Sigmoid()     #这里的激活函数可以选择很多,也可以用Sign()、Linear()、ReLU()等。  要改成:self.activate = torch.nn.ReLU().
        
        
    def forward(self, x):
        # x = self.sigmoid(self.linear(x))    #直接输入8->1
        x = self.sigmoid(self.linear1(x))
        x = self.sigmoid(self.linear2(x))
        x = self.sigmoid(self.linear3(x))
        return x    
    
model = Model()


criterion = torch.nn.BCELoss(size_average=True)
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)




for epoch in range(100):
    #Forward
    y_pred = model(x_data)      #
    loss = criterion(y_pred,y_data)
    print(epoch,loss.item())
    
    #Backward
    optimizer.zero_grad()
    loss.backward()
    
    
    #update
    optimizer.step()
    
    
    
    

 

©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页