pytorch 入门学习使用逻辑斯蒂做二分类

pytorch 入门学习使用逻辑斯蒂做二分类

使用pytorch实现逻辑斯蒂做二分类

import  torch
import  torchvision
import  numpy as np
import  torch.nn.functional as F
import matplotlib.pyplot as plt

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

class LogisticRegressionModel(torch.nn.Module):
    def __init__(self):
        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()

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

for epoch in range(10000):
    y_pred = model(x_data)
    loss = criterion(y_pred,y_data)
    print(epoch,loss.item())

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

#test and visialization
x = np.linspace(0,10,200)
x_t = torch.Tensor(x).view((200,1))
y_t = model(x_t)
y = y_t.data.numpy()
plt.plot(x,y)
plt.xlabel('Hours')
plt.ylabel('Probability of Pass')
plt.grid()
plt.show()

在这里插入图片描述

9991 0.255062073469162
9992 0.2550414502620697
9993 0.2550209164619446
9994 0.2550000548362732
9995 0.2549794316291809
9996 0.2549586296081543
9997 0.2549380660057068
9998 0.25491729378700256
9999 0.25489675998687744

猜你喜欢

转载自blog.csdn.net/weixin_41281151/article/details/108239636