PyTorch基本用法(五)——分类

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

本文主要是关于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
import torch
import matplotlib.pyplot as plt
import torch.nn.functional as F

from torch.autograd import Variable

# 许多没解释的东西可以去查文档, 文档中都有, 已查过
# pytorch文档: http://pytorch.org/docs/master/index.html
# matplotlib文档: https://matplotlib.org/

# 随机算法的生成种子
torch.manual_seed(1)

# 生成数据
n_data = torch.ones(100, 2)


# 类别一的数据
x0 = torch.normal(2 * n_data, 1)
# 类别一的标签
y0 = torch.zeros(100)

# 类别二的数据
x1 = torch.normal(-2 * n_data, 1)
# 类别二的标签
y1 = torch.ones(100)

# x0, x1连接起来, 按维度0连接, 并指定数据的类型
x = torch.cat((x0, x1), 0).type(torch.FloatTensor)
# y0, y1连接, 由于只有一维, 因此没有指定维度, torch中标签类型必须为LongTensor
y = torch.cat((y0, y1), ).type(torch.LongTensor)


# x,y 转为变量, torch只支持变量的训练, 因为Variable中有grad
x, y = Variable(x), Variable(y)
1
2
3
# 绘制数据散点图
plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c = y.data.numpy(), s = 100, lw = 0, cmap = 'RdYlGn')
plt.show()

png

1
2
3
4
5
6
7
8
9
10
11
12
# 定义分类网络
class Net(torch.nn.Module):

def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden)
self.prediction = torch.nn.Linear(n_hidden, n_output)

def forward(self, x)
x = F.relu(self.hidden(x))
x = self.prediction(x)
return x
1
2
3
# 定义网络
net = Net(n_feature = 2, n_hidden = 10, n_output = 2)
print(net)
Net (
  (hidden): Linear (2 -> 10)
  (prediction): Linear (10 -> 2)
)
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
# 定义优化方法
optimizer = torch.optim.SGD(net.parameters(), lr = 0.02)
# 定义损失函数
loss_func = torch.nn.CrossEntropyLoss()

plt.ion()

# 训练过程
for i in xrange(100):
prediction = net(x)
loss = loss_func(prediction, y)

optimizer.zero_grad()
loss.backward()
optimizer.step()

if i % 2 == 0:
plt.cla()
# 获取概率最大的类别的索引
prediction = torch.max(F.softmax(prediction), 1)[1]
# 将输出结果变为一维
pred_y = prediction.data.numpy().squeeze()
target_y = y.data.numpy()
plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c = pred_y, s = 100, lw = 0, cmap = 'RdYlGn')
# 计算准确率
accuracy = sum(pred_y == target_y) / 200.0
plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict = {'size': 10, 'color': 'red'})
plt.pause(0.1)

plt.ioff()
plt.show()

png

1
2
3
4
# torch.max用法
a = torch.randn(4, 4)
print a
print torch.max(a, 1)
-1.8524 -1.0491  0.5382 -0.5129
 0.1233 -0.1821  2.1519 -1.4547
-1.0267  0.2644 -0.8832 -0.2647
 0.3944 -1.2512 -0.1158  0.5071
[torch.FloatTensor of size 4x4]

(
 0.5382
 2.1519
 0.2644
 0.5071
[torch.FloatTensor of size 4]
, 
 2
 2
 1
 3
[torch.LongTensor of size 4]
)

参考资料

  1. https://www.youtube.com/user/MorvanZhou
如果有收获,可以请我喝杯咖啡!