#利用包构建Variable回归
import torch
from torch import nn
from torch.autograd import Variable
from matplotlib import pyplot as plt
import numpy as np
#例子
#https://blog.csdn.net/liuzuoping/article/details/101359169
x0 = torch.normal(4 * torch.ones(200, 2))
y0 = torch.zeros(200)
x1 = torch.normal(-4 * torch.ones(200, 2))
y1 = torch.ones(200)
x = torch.cat((x0, x1)).type(torch.FloatTensor)#合并
y = torch.cat((y0, y1)).type(torch.FloatTensor)#合并
#相当于sigmiod函数
#可以快速构建
#写法一 net = nn.Sequential( nn.Linear(num_inputs, 1) # 此处可以添加其它层 )
# 写法二 # net = nn.Sequential() # net.add_module('linear', nn.Linear(num_inputs, 1)) # net.add_module………
# 写法三 # from collections import OrderedDict # net = nn.Sequential(OrderedDict([ # ('linear', nn.Linear(num_inputs, 1)) # # ……]))
class LogisticNet(nn.Module):
def __init__(self):
super(LogisticNet, self).__init__()
self.lr = nn.Linear(2, 1)
self.sm = nn.Sigmoid()
def forward(self, a):
a = self.lr(a)
a = self.sm(a)
return a
logistic_model = LogisticNet()#out
criterion = nn.BCELoss()#loss函数
optimizer = torch.optim.SGD(logistic_model.parameters(), lr=0.00001, momentum=0.8)#处理 ir=0.1 momentum=0.8
for epoch in range(40000):
x_data = Variable(x)#没有区别
y_data = Variable(y)
out = logistic_model(x_data)#logistic_model相当于sigmiod函数
loss = criterion(out, y_data)#out相当于一个公式的值
print_loss = loss.data.item()
mask = out.ge(0.5).float()#大于0.5就等于1,小于0.5就等于0
correct = (mask == y_data).sum()#对的有多少个,加起来
accuracy= correct.item() / x_data.size(0)#除以总的长度得到准确率
optimizer.zero_grad()#梯度清零
loss.backward()
optimizer.step()
if (epoch + 1) % 20 == 0:
print('{}代'.format(epoch + 1))
print('loss 为 {:.4f}'.format(print_loss))
print('accuracy 为 {:.4f}'.format(accuracy))
# 参数输出
w0, w1 = logistic_model.lr.weight[0]
w0 = float(w0.item())
w1 = float(w1.item())
b = float(logistic_model.lr.bias.item())
print('w0:{}\n'.format(w0), 'w1:{}\n'.format(w1), 'b:{0}'.format(b))
plt.scatter(x_data.numpy()[:,0],x_data.numpy()[:,1],c=y_data.numpy(),s=100, lw=0, cmap='RdYlGn')
plot_x=np.arange(-7,7,0.1)
plot_y=(-w0*plot_x-b)/w1
plt.plot(plot_x,plot_y)
plt.show()