我的博客

pytorch 基础用法:线性回归和逻辑回归

目录
  1. 线性回归(LinearRegression)
  2. 逻辑回归(LogisticRegression)
    1. 生成数据
    2. 可视化
    3. 训练模型
1
2
torch.__version__
'1.3.1+cpu'

线性回归(LinearRegression)

下图反映了 100 次迭代中,模型(红色直线)对训练数据(蓝色点)的拟合不断加强。

线性回归收敛过程

以下代码来自数据科学杂谈公众号的Pytorch教程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import torch
import matplotlib.pyplot as plt

torch.manual_seed(10)#随机数种子
lr = 0.1 #学习率

#创建训练数据
x = torch.rand(20,1)*10 #shape(20,1)
y = 2*x + (5 + torch.randn(20,1)) #shape(20,1)

#构建线性回归参数
w = torch.randn((1),requires_grad=True)#随机初始化w,要用到自动梯度求导
b = torch.zeros((1),requires_grad=True)#使用0初始化b,要用到自动梯度求导

for iteration in range(1000):

#前向传播
wx = torch.mul(w,x) # w*x
y_pred = torch.add(wx,b) # y = w*x + b

#计算 MSE loss
loss = (0.5*(y-y_pred)**2).mean()

#反向传播
loss.backward()

#更新参数
b.data.sub_(lr*b.grad) # b = b - lr*b.grad
w.data.sub_(lr*w.grad) # w = w - lr*w.grad

#绘图
if iteration % 20 == 0:
plt.scatter(x.data.numpy(),y.data.numpy())
plt.plot(x.data.numpy(),y_pred.data.numpy(),'r-',lw=5)
plt.text(2,20,'Loss=%.4f'%loss.data.numpy(),fontdict={'size':20,'color':'red'})
plt.xlim(1.5,10)
plt.ylim(8,28)
plt.title("Iteration:{}\nw:{},b:{}".format(iteration,w.data.numpy(),b.data.numpy()))
plt.pause(0.5)

if loss.data.numpy() < 1:#停止条件
break

逻辑回归(LogisticRegression)

逻辑回归的收敛.png

以下代码是参考网上的资料自己实现的

生成数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import torch
import matplotlib.pyplot as plt


n_data = torch.ones(100, 2)
xy0 = torch.normal(2 * n_data, 1) # 生成均值为2.标准差为1的随机数组成的矩阵 shape=(100, 2)
c0 = torch.zeros(100)
xy1 = torch.normal(-2 * n_data, 1) # 生成均值为-2.标准差为1的随机数组成的矩阵 shape=(100, 2)
c1 = torch.ones(100)

x,y = torch.cat((xy0,xy1),0).type(torch.FloatTensor).split(1, dim=1)
x = x.squeeze()
y = y.squeeze()
c = torch.cat((c0,c1),0).type(torch.FloatTensor)

x 是 200 个点的 x 坐标,y 是 200 个点的 y 坐标,c 是这 200 个点的类别,前 100 个点是

可视化

1
2
plt.scatter(x.data.numpy(),y.data.numpy(), c=c.data.numpy(), s=100, cmap='RdYlGn')
plt.show()

结果如下

两种类型的数据分布

训练模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
lr = 0.02 #学习率


xx = torch.arange(-4, 5)
#构建线性回归参数
w = torch.tensor([1.,],requires_grad=True)#随机初始化w,要用到自动梯度求导
b = torch.zeros((1),requires_grad=True)#使用0初始化b,要用到自动梯度求导

for iteration in range(1000):
#前向传播
loss = ((torch.sigmoid(x*w+b-y) - c)**2).mean()
#反向传播
loss.backward()
#更新参数
b.data.sub_(lr*b.grad) # b = b - lr*b.grad
w.data.sub_(lr*w.grad) # w = w - lr*w.grad
#绘图
if iteration % 3 == 0:
plt.scatter(x.data.numpy(),y.data.numpy(), c=c.data.numpy(), s=100, cmap='RdYlGn')
yy = w*xx + b
plt.plot(xx.data.numpy(),yy.data.numpy(),'r-',lw=5)
plt.text(-4,2,'Loss=%.4f'%loss.data.numpy(),fontdict={'size':20,'color':'red'})
plt.xlim(-4,4)
plt.ylim(-4,4)
plt.title("Iteration:{}\nw:{},b:{}".format(iteration,w.data.numpy(),b.data.numpy()))
plt.show(0.5)

if loss.data.numpy() < 0.01:#停止条件
break

参考资料:

用pytorch实现逻辑回归
逻辑回归(logistic regression)原理详解
PyTorch基础入门四:PyTorch搭建逻辑回归模型进行分类

评论无需登录,可以匿名,欢迎评论!