Pytorch ABC 1

因为同学推荐,今天安装Pytorch框架。据说比Tensorflow更方便,也更省内存。
在介绍中,Pytorch自称为deep框架的numpy。

安装

非常简单,人性化。一行代码即可,比其他框架容易。

Pytorch ABC 1_第1张图片
Pytorch安装

基本语法

定义张量

x = torch.Tensor(5, 3)
print(x)
y = torch.FloatTensor(5, 3)
print(y)
 0.0000e+00  0.0000e+00 -7.8785e+31
 4.5577e-41 -7.8789e+31  4.5577e-41
 5.0649e-38  0.0000e+00  5.0649e-38
 0.0000e+00  4.0357e-40  1.6772e-37
 8.9683e-44  0.0000e+00 -7.8785e+31
[torch.FloatTensor of size 5x3]


 0.0000e+00  0.0000e+00 -7.8785e+31
 4.5577e-41 -7.8787e+31  4.5577e-41
 5.0649e-38  0.0000e+00  5.0649e-38
 0.0000e+00  0.0000e+00  1.6771e-37
 8.9683e-44  0.0000e+00  0.0000e+00
[torch.FloatTensor of size 5x3]

可见torch.Tensor 默认构造一个FloatTensor。
简单计算

计算加法有以下几种写法

x = torch.randn(5, 3)
y = torch.randn(5, 3)
print x + y
print torch.add(x, y)
-0.7518  0.0857  0.5324
 1.2734 -0.9105 -1.1632
-1.5461 -0.1408  1.3701
 1.6882 -2.6038 -0.3492
-1.1691  0.3820 -1.1746
[torch.FloatTensor of size 5x3]


-0.7518  0.0857  0.5324
 1.2734 -0.9105 -1.1632
-1.5461 -0.1408  1.3701
 1.6882 -2.6038 -0.3492
-1.1691  0.3820 -1.1746
[torch.FloatTensor of size 5x3]
result = torch.Tensor(5, 3)
torch.add(x, y, out=result)
print result
-0.7518  0.0857  0.5324
 1.2734 -0.9105 -1.1632
-1.5461 -0.1408  1.3701
 1.6882 -2.6038 -0.3492
-1.1691  0.3820 -1.1746
[torch.FloatTensor of size 5x3]
y.add_(x)
-0.7518  0.0857  0.5324
 1.2734 -0.9105 -1.1632
-1.5461 -0.1408  1.3701
 1.6882 -2.6038 -0.3492
-1.1691  0.3820 -1.1746
[torch.FloatTensor of size 5x3]

Slicing
和Numpy相同

print x[:]
print x[1:3, :]
-0.1647 -0.4870 -0.1755
-0.3148 -0.5922 -0.2053
-0.5448 -1.4650  2.0470
 2.3983 -1.5116  0.6507
-1.2435 -0.1560 -0.8927
[torch.FloatTensor of size 5x3]


-0.3148 -0.5922 -0.2053
-0.5448 -1.4650  2.0470
[torch.FloatTensor of size 2x3]

与Numpy变量之间的转换

>>> a = torch.ones(5)
>>> b = a.numpy()
>>> a

 1
 1
 1
 1
 1
[torch.FloatTensor of size 5]

>>> b
array([ 1.,  1.,  1.,  1.,  1.], dtype=float32)

注意,在运算的时候,它们是绑定的:

>>> a.add_(1)

 2
 2
 2
 2
 2
[torch.FloatTensor of size 5]

>>> b
array([ 2.,  2.,  2.,  2.,  2.], dtype=float32)

放在CUDA中运算

>>> torch.cuda.is_available()
True
>>> x = x.cuda()
>>> y = y.cuda()
>>> x+y

   0.0983    0.5931    0.4211
   0.6717    0.9579    0.4118
   0.5332    0.1976    0.6919
   0.2896    0.3155    0.1421
   0.7828  409.2463    0.8346
[torch.cuda.FloatTensor of size 5x3 (GPU 0)]

你可能感兴趣的:(Pytorch ABC 1)