【pytorch_4】线性回归与逻辑回归例程

基于pytorch的线性回归和逻辑回归代码比较。
框架结构设计五大步骤:

  1. prepare dataset
  2. design model using class
  3. construct loss and optimizer
  4. Training cycle
  5. testing
#线性回归
import torch

#prepare dataset
x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[2.0],[4.0],[6.0]])

# design model using class
class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel,self).__init__()
        self.linear = torch.nn.Linear(1,1) #input channel;output channel
        
    def forward(self,x):
        y_pred = self.linear(x)
        return y_pred
model = LinearModel()

# construct loss and optimizer
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)

# Training cycle
for epoch in range(1000):
    y_pred = model(x_data)
    loss = criterion(y_pred,y_data)
    print(epoch,loss.item())
    
    optimizer.zero_grad()
    loss = loss.requires_grad_()
    loss.backward()
    optimizer.step()

print('w-',model.linear.weight.item())
print('b-',model.linear.bias.item()) 

# testing
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_pred=',y_test.data)
#逻辑回归
import torch

#prepare dataset
x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[0],[0],[1]])

# design model using class
class LogisticRegressionModel(torch.nn.Module):
    def __init__(self):
        super(LogisticRegressionModel,self).__init__()
        self.linear = torch.nn.Linear(1,1) #input channel;output channel
        
    def forward(self,x):
        y_pred = torch.sigmoid(self.linear(x))
        return y_pred
model = LogisticRegressionModel()

# construct loss and optimizer
criterion = torch.nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)

# Training cycle
for epoch in range(1000):
    y_pred = model(x_data)
    loss = criterion(y_pred,y_data)
    print(epoch,loss.item())
    
    optimizer.zero_grad()
    loss = loss.requires_grad_()
    loss.backward()
    optimizer.step()

print('w-',model.linear.weight.item())
print('b-',model.linear.bias.item()) 

# testing
x_test = torch.Tensor([[3.0]])
y_test = model(x_test)
print('y_pred=',y_test.data) 

参考:《PyTorch深度学习实践》完结合集

你可能感兴趣的:(Pytorch学习专栏,深度学习,逻辑回归,神经网络)