数据:
连接: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()