pytorch + python实现逻辑回归(二分类)

数据:

连接:https://pan.baidu.com/s/1-v5R_Yvb94GxafH8e9QDkg 

提取码:0kle

代码:

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

#从data.txt中读入点
with open('data.txt','r') as f:
    data_list = f.readlines()
    print(data_list)
    data_list = [i.split('\n')[0] for i in data_list]
    print(data_list)
    data_list = [i.split(',') for i in data_list]
    print(data_list)
    data = [(float(i[0]),float(i[1]),float(i[2])) for i in data_list]
    print(data)
# 标准化
x0_max = max([i[0] for i in data])
x1_max = max([i[1] for i in data])
data = [(i[0]/x0_max,i[1]/x1_max,i[2]) for i in data]
# x_data = [(float(i[0]), float(i[1])) for i in data_list]
# y_data = [(float(i[2])) for i in data_list]

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]
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()

#将数据转换成numpy类型,接着转换成Tensor类型
np_data = np.array(data,dtype='float32')#转成numpy array
x_data = torch.from_numpy(np_data[:,0:2])#转换成Tensor,大小是[100,2]
y_data = torch.from_numpy(np_data[:,-1]).unsqueeze(1)#转成tensor,大小是[100,1]

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

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

criterion = nn.BCELoss()
optimizer = optim.SGD(logistic_model.parameters(),lr=1e-3,momentum=0.9)

for epoch in range(50000):
    if torch.cuda.is_available():
        x = Variable(x_data).cuda()
        y = Variable(y_data).cuda()
    else:
        x = Variable(x_data)
        y = Variable(y_data)

    #向前传播
    out = logistic_model(x_data)
    loss = criterion(out,y_data)
    print_loss = loss.item()
    #向后传播
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    #计算正确率
    mask = out.ge(0.5).float()
    acc = (mask == y_data).sum().item()/y_data.shape[0]

    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))

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.show()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值