PyTorch学习之路:Logistic回归

本代码参考廖星宇《深度学习入门之PyTorch》中示例代码,手动复现而来,仅供个人学习使用,侵删。

import torch
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
import matplotlib.pyplot as plt

#逻辑回归模型
class LogisticRegression(nn.Module):
    def __init__(self):
        super(LogisticRegression, self).__init__()
        self.lr = nn.Linear(2, 1)
        self.sm = nn.Sigmoid()

    def forward(self, x):
        x = self.lr(x)
        x = self.sm(x)
        return x

if __name__ == '__main__':
    #从data.txt中读取数据
    with open('data.txt', 'r') as f:
        data_list = f.readlines()
        data_list = [i.split('\n')[0] for i in data_list]
        data_list = [i.split(',') for i in data_list]
        data = [(float(i[0]), float(i[1]), float(i[2])) for i in data_list]
        data = torch.Tensor(data)

    logistic_model = LogisticRegression()
    if torch.cuda.is_available():
        logistic_model.cuda()

    #定义损失函数和优化函数
    criterion = nn.BCELoss()
    optimizer = torch.optim.SGD(logistic_model.parameters(), lr=1e-3, momentum=0.9)

    #训练模型
    for epoch in range(50000):
        if torch.cuda.is_available():
            x = Variable(data[:, 0:2]).cuda()
            y = Variable(data[:, 2]).cuda().unsqueeze(1)
        else:
            x = Variable(data[:, 0:2])
            y = Variable(data[:, 2]).unsqueeze(1)
        #前向传播
        out = logistic_model(x)
        loss = criterion(out, y)
        print_loss = loss.item()
        mask = out.ge(0.5).float()#大于0.5就等于1,小于0.5就等于0
        correct = (mask == y).sum()
        acc = correct.item() / x.size(0)
        #反向传播
        optimizer.zero_grad()#梯度归零
        loss.backward()
        optimizer.step()#更新参数
        if(epoch + 1) % 1000 == 0:
            print('*'*10)
            print('epoch{}'.format(epoch+1))
            print('loss is {:.4f}'.format(print_loss))
            print('acc is {:.4f}'.format(acc))


    #通过matplotlib将数据画出来
    x0 = list(filter(lambda x:x[-1] == 0.0, data))
    x1 = list(filter(lambda x: x[-1] == 1.0, data))
    plot_x0_0 = [i[0] for i in x0]
    plot_x0_1 = [i[1] for i in x0]
    plot_x1_0 = [i[0] for i in x1]
    plot_x1_1 = [i[1] for i in x1]

    w0, w1 = logistic_model.lr.weight[0]
    w0 = w0.item()
    w1 = w1.item()
    b = logistic_model.lr.bias.item()
    plot_x = np.arange(30, 100, 0.1)
    plot_y = (-w0 * plot_x - b) / w1
    plt.plot(plot_x, plot_y)

    plt.plot(plot_x0_0, plot_x0_1, 'ro', label='x_0')
    plt.plot(plot_x1_0, plot_x1_1, 'bo', label='x_1')
    plt.legend(loc='best')
    plt.show()

PyTorch学习之路:Logistic回归_第1张图片

你可能感兴趣的:(PyTorch学习之路)