pytorch的0.4.0版本相对0.3.0做了一些改进,总体上使用更加方便。
不加初始化地构建矩阵,使用torch.empty(row, column).
随机初始化矩阵,使用torch.rand(row, column).
可以和numpy中定义一些矩阵一样,如
x = torch.zeros(5, 3, dtype=torch.float)
x = torch.tensor([5.5, 3]) #构建指定元素的矩阵
可以在已有的tensor基础上新建tensor:
x = x.new_ones(5, 3, dtype=torch.double) # new_* 方法定义新的tensor
x = torch.randn_like(x, dtype=torch.float) # 重写数据类型,尺寸保持一致
x.size()的结果是torch.Size([rows, columns]),
torch.Size
实际上是一个元组, 因而支持元组操作。x.size(0)为行数,列则为1.
加法的语法:直接使用‘+’号;torch.add(x, y); torch.add(x, y, out=result)。
任何要原地改动tensor的操作,需要加 _
. 比如: x.copy_(y)
, x.t_()
, x.add_(y)will change x
.
索引方法和numpy一样,如 x[:, 1]。
使用torch.view(v1,v2,...)来resize或者reshape tensor,例如
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
Out: torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
如果一个tensor只有一个元素,那么可以使用
.item()
方法取出这个元素作为普通的python数字。
tensor和numpy之间的转化与0.3.0版本一样,由tensor向numpy转化使用例子如下,注意这种操作的结果是tensor和numpy始终同变化:
a = torch.ones(5)
print(a)
Out: tensor([ 1., 1., 1., 1., 1.])
b = a.numpy()
print(b)
Out: [1. 1. 1. 1. 1.]
a.add_(1)
print(a)
print(b)
Out: tensor([ 2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]
由numpy向tensor转化的例子如下,二者依然是同步变化的(即改变其中一个,另一个自动变化):
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
Out: [2. 2. 2. 2. 2.]
tensor([ 2., 2., 2., 2., 2.], dtype=torch.float64)
tensor可以通过使用
.to
方法移动到任何设备上,这是0.4.0版本的一个优点。
# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!