Open pengsida opened 6 years ago
下面这个代码我测试了,是没有问题的:
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
import torch
from torch import nn
from torch import optim
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]
np_data=np.array(data,dtype='float32')
x_data=torch.from_numpy(np_data[:,0:2])
y_data=torch.from_numpy(np_data[:,-1]).unsqueeze(1)
#draw
x0=list(filter(lambda x:x[-1]==0.0,data))
x1=list(filter(lambda x:x[-1]==1.0,data))#分类
plot_x0_x=[i[0] for i in x0]
plot_x0_y=[i[1] for i in x0]
plot_x1_x=[i[0] for i in x1]
plot_x1_y=[i[1] for i in x1]
plt.plot(plot_x0_x,plot_x0_y,'ro',label='0')
plt.plot(plot_x1_x,plot_x1_y,'bo',label='1')
plt.legend(loc='best')
#definite model
class LogisticRegression(nn.Module):
def __init__(self):
super().__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
model=LogisticRegression()
criterion=nn.BCELoss(size_average=True)#二分类的损失函数
optimizer=torch.optim.SGD(model.parameters(),lr=0.001)#动量是0.9
for epoch in range(100000):
predict=model(x_data)
loss=criterion(predict, y_data)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print('times[{}/{}],loss:{}'.format(epoch+1,1000,loss))
w = list(model.parameters())
w0 = w[0].data.numpy()
w1 = w[1].data.numpy()
x_axis = np.linspace(20, 100, 1000)
y_axis = -(w1[0] + x_axis*w0[0][0]) / w0[0][1]
line_up, = plt.plot(x_axis, y_axis,'r--', label='gradient descent')
plt.legend(handles=[line_up])
plt.xlabel('X(1)')
plt.ylabel('X(2)')
plt.show()
还有个问题是,你的代码风格不是很好,建议网上搜一下python代码规范
我看了你写的https://github.com/Wegnery219/pytorch-learning/blob/master/logistic/logistic.ipynb
里面[18]虽然没什么问题,但是我在运行的过程中出现了严重的梯度消失现象,这有点奇怪,不知道你有没有遇到这个问题。初步猜测和初始化有关
你最后的cell代码写错了,建议参考一下logistic regression的一些博客:https://m-alcu.github.io/blog/2018/02/10/logit-pytorch/
你用的pytorch版本有点落后,建议参考pytorch.org上tutorial目前的写法