pytorch实现logisticRegressionModel

1,代码如下

import imp
from statistics import mode
import torch.nn.functional as F
import torch

# 1, Prepare data

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

# 2, Design model

class LogisticRegressionModel(torch.nn.Module):
    def __init__(self) -> None: # 初始化函数
        super(LogisticRegressionModel,self).__init__()
        self.linear = torch.nn.Linear(1,1)

    def forward(self,x): # 前馈计算
        y_pred = F.sigmoid(self.linear(x))
        return y_pred

model = LogisticRegressionModel()

# 3, Select criterion and optimizer (using PyTorch API)

criterion = torch.nn.BCELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(),lr=0.01) # 优化器(梯度下降)

# 4, 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.backward()
    optimizer.step()

print("w = ",model.linear.weight.item())
print("b = ",model.linear.bias.item())


x_test = torch.Tensor([[4.0]])
y_test = model(x_test)

print("y_pred = ",y_test.data)

全部评论

相关推荐

不愿透露姓名的神秘牛友
09-30 19:49
起名星人:蛮离谱的,直接要求转投销售
投递汇川技术等公司10个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务