60分钟闪电战之一_tensor

0.官方发言

pytorch官网给了一个60分钟教程,这个一定一定要看看,它讲了很多pytorch的特性。

1. Tensor

Tensor与Numpy中ndarrays类似,但是在Pytorch中,tensor可以在GPU上面运算。
pytorch的import

1
2
from __future__ import print_function
import torch

1.1 创建矩阵

1
2
3
4
5
6
7
8
9
10
#API
x = torch.empty(5,3)#没有初始化的5x3矩阵
x = torch.rand(5,3)#随机初始化的矩阵
x = torch.zeros(5,3, dtype=torch.long)#初始化为类型为long值为0的矩阵
#数据
x = torch.tensor([5.5, 4])
x = torch.from_numpy(np.array([5.5,4]))
#已经存在的tensor
x = x.new_ones(2,2,dtype=torch.double)#new_*
x = torch.randn_like(x, dtype=torch.float)#*_like

1.2 矩阵操作

add的三种方式

A+B:

1
2
3
x  = torch.ones(5,3)
y = torch.rand(5, 3)
print("x+y:n", x+y)

torch.add(A,B):

可以指定输出变量

1
2
3
4
print("torch.add(x,y):n", torch.add(x,y))
result = torch.empty(5,3)
torch.add(x,y, out=result)
print("通过形参指定输出变量:n", result)

A.add_(B):

本地操作API后缀_

1
2
3
4
y.add_(x)
print("本地操作y.add_(x):n", y)

print("所有在原地操作的变量均用_表示,比如x.copy_(y),x.t_()")

类似NumPy的索引方式

1
2
3
print("可以使用Numpy-like的所有bells和whistles,like:")
print("x[:,1]:n", x[:,1])
print("x[2:4, 0:2]:n", x[2:4, 0:2])

使用torch.view()做Resizing

1
2
3
4
5
6
7
x = torch.randn(4,4)
y = x.view(16)
z = x.view(-1,8)
print("使用view改变tensor的shape:n",
x.size(),
y.size(),
z.size())

torch.item()方法

1
2
x = torch.randn(1)
print("对于只有一个元素的tensor,可以使用.item()得到其值并且转换为python数字:n",x, x.item())

还有更多关于tensor的操作here

TODO:
使用树状图进行总结,一些操作和方法需要解释理论

1.3 NumPy Bridge

基于这个可以和numpy无缝结合

torch tensor => numpy ndarray

1
2
3
4
5
6
7
8
9
print("Converting a Torch Tensor to a NumPy Array:n")
a = torch.ones(5)
b = a.numpy()
print("使用torch.numpy(), 把tensor转换为numpy类型的数据:n",a, b)
print("来看看numpy数组的值怎么变换的")
a.add_(1)
print("a.add_(1):n", a, b)
np.add(b, 1, out=b)
print("np.add(b, 1, out=b):n", a, b)

numpy ndarray => torch tensor

1
2
3
4
5
6
7
8
print("Converting NumPy array to Torch Tensor:n")
a = np.ones(4)
b = torch.from_numpy(a)
print("使用torch.from_numpy()将numpy数组转换为tensor:n",a,b)
np.add(a, 1, out=a)
print("np.add(a,1,out=a):n",a,b)
b.add_(1)
print("b.add_(1):n", a,b)

通过运行可以看出:

1
2
3
print("n 可以看出, torch.numpy()和torch.from_numpy()是把原来的数据,"
"重新用torch或numpy重新解释了一遍,"
"修改他们中的一个另外一个也会接着改变")

1.4 CUDA tensor

创建时指定device

1
2
x = torch.randn(5,5,device=torch.device("cpu"))
y = torch.ones_like(x, device=torch.device("cuda"))

划重点,就是cuda和cpu直接的切换

torch.to()

1
2
3
4
5
device = torch.device("cuda")
x = x.to(device)
z = x+y
print("z在GPU上:n",z)
print("z在CPU上:n",z.to("cpu", torch.double))

.to can also change dtype together!

torch.cuda() or torch.cpu()

1
2
3
x = torch.randn(5,5)
print("x.cuda():n", x.cuda())
print("x.cpu():n", x.cpu())

这种切换方法,让你尽情切换