标签:bsp lin range war col rop sig turn mod
(1)相较于线性回归,使用激活函数sigmoid函数,将结果以0-1之间呈现
(2)损失函数计算:cross-entropy交叉熵
1 import torch 2 3 #data 4 x_data = torch.Tensor([[1.0], [2.0], [3.0]]) 5 y_data = torch.Tensor([[0], [0], [1]]) 6 7 #model 8 class LogisticRegressionModel(torch.nn.Module): 9 def __init__(self): 10 super(LogisticRegressionModel, self).__init__() 11 self.linear = torch.nn.Linear(1, 1) 12 13 def forward(self, x): 14 y_pred = torch.sigmoid(self.linear(x)) 15 return y_pred 16 17 18 19 model=LogisticRegressionModel() 20 21 # loss & optimizer 22 criterion=torch.nn.BCELoss(size_average=False) 23 optimizer=torch.optim.SGD(model.parameters(),lr=0.01) 24 25 #forward & backward & updata 26 for epoch in range(100): 27 y_pred=model(x_data) 28 l=criterion(y_pred,y_data) 29 print("epoch=",epoch,"loss=",l.item()) 30 31 optimizer.zero_grad() 32 l.backward() 33 optimizer.step() 34 35 print (‘w = ‘,model.linear.weight.item()) 36 print(‘b = ‘,model.linear.bias.item()) 37 38 x_test = torch.Tensor([[4.0]]) 39 y_test = model(x_test) 40 print(‘y_pred = ‘, y_test.data)
标签:bsp lin range war col rop sig turn mod
原文地址:https://www.cnblogs.com/miosk/p/14670977.html