1.算术操作
1.加法
x = torch.rand(5, 3)
y = torch.rand(5, 3)
#【1】直接+
print(x + y)
#【2】add函数
print(torch.add(x, y))
result = torch.empty(5, 3)
torch.add(x, y, out=result)#指定输出
print(result)
#【3】add_覆盖函数
y.add_(x)
print(y)
#注:PyTorch操作inplace版本都有后缀_, 例如x.copy_(y), x.t_()
2.索引
索引出来的结果与原数据共享内存,也即修改一个,另一个会跟着修改。
x = torch.rand(5, 3)
y = torch.rand(5, 3)
#【1】普通索引
y = x[0, :]
y += 1
print(y)
print(x[0, :]) # 源tensor也被改了
#【2】在指定维度上选取
index_select(input, dim, index)#选取某些行、某些列
#【3】条件选取
masked_select(input, mask)#a[a>0],使用ByteTensor进行选取
#【4】非0元素的下标
nonzero(input)
#【5】根据index,在dim维度上选取数据
gather(input, dim, index)#输出的size与index一样
3.改变形状
1.用view()
来改变Tensor的形状。
-
注意view()返回的新Tensor与源Tensor虽然可能有不同的size,但是是
共享data
的,也即更改其中的一个,另外一个也会跟着改变。(顾名思义,view仅仅是改变了对这个张量的观察角度,内部数据并未改变) -
虽然view返回的Tensor与源Tensor是共享data的,但是依然是一个新的Tensor(因为Tensor除了包含data外还有一些其他属性),二者id(内存地址)并不一致。
x = torch.rand(5, 3)
y = x.view(15)
z = x.view(-1, 5) # -1所指的维度可以根据其他维度的值推出来
print(x.size(), y.size(), z.size())
2.用reshape()
来改变Tensor的形状。
此函数并不能保证返回的是其拷贝,所以不推荐使用。
x = torch.rand(5, 3)
y = x.reshape(15)
3.先clone()
在view()
以返回一个真正的副本。
使用clone还有一个好处是会被记录在计算图中,即梯度回传到副本时也会传到源Tensor。
x = torch.rand(5, 3)
x_cp = x.clone().view(15)
x -= 1
print(x)
print(x_cp)
4.用item()
来改变Tensor的形状。
可以将一个标量Tensor转换成一个Python number。
x = torch.randn(1)
print(x)
print(x.item())
2.线性代数
trace #对角线元素之和(矩阵的迹)
diag #对角线元素
triu/tril #矩阵的上三角/下三角,可指定偏移量
mm/bmm #矩阵乘法,batch的矩阵乘法
addmm/addbmm/addmv/addr/baddbmm.. #矩阵运算
t #转置
dot/cross #内积/外积
inverse #求逆矩阵
svd #奇异值分解
PyTorch中的Tensor支持超过一百种操作,包括转置
、索引
、切片
、数学运算
、线性代数
、随机数
等等。
3.广播机制
前面我们看到如何对两个形状相同的Tensor做按元素运算。当对两个形状不同的Tensor按元素运算时,可能会触发广播(broadcasting)机制:先适当复制元素使这两个Tensor形状相同后再按元素运算。
x = torch.arange(1, 3).view(1, 2)
print(x)
y = torch.arange(1, 4).view(3, 1)
print(y)
print(x + y)
输出:
tensor([[1, 2]])
tensor([[1],
[2],
[3]])
tensor([[2, 3],
[3, 4],
[4, 5]])
相当于:
tensor([[1, 2],
[1, 2],
[1, 2]])
tensor([[1, 1],
[2, 2],
[3, 3]])
tensor([[2, 3],
[3, 4],
[4, 5]])
4.运算的内存开销
索引操作是不会开辟新内存的,而像y = x + y
这样的运算是会新开内存的,然后将y指向新内存。
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
y = y + x
print(id(y) == id_before) # False
#Python自带的id函数:如果两个实例的ID一致,那么它们所对应的内存地址相同
如果想指定结果到原来的y的内存:
(1)可以使用前面介绍的索引来进行替换操作。
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
y[:] = y + x
print(id(y) == id_before) # True
(2)可以使用运算符全名函数中的out参数
或者自加运算符+=
(也即add_()
)。
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
#【1】out参数
torch.add(x, y, out=y)
#【2】+=
y += x
#【3】add_
y.add_(x)
print(id(y) == id_before) # True
5.torch张量和Numpy数组相互转换
- 所有在CPU上的Tensor(除了CharTensor)都支持与NumPy数组相互转换。
- 我们很容易用
tensor.numpy()
和torch.from_numpy()
将Tensor和NumPy中的数组相互转换。但是需要注意的一点是: 这两个函数所产生的的Tensor和NumPy中的数组共享相同的内存
(所以他们之间的转换很快),改变其中一个时另一个也会改变!!! - 还有一个常用的将NumPy中的array转换成Tensor的方法就是
torch.tensor()
, 需要注意的是,此方法总是会进行数据拷贝(就会消耗更多的时间和空间),所以返回的Tensor和原来的数据不再共享内存
。
- 我们很容易用
- 用方法
to()
可以将Tensor在CPU和GPU(需要硬件支持)之间相互移动。
(1)Tensor转NumPy
a = torch.ones(5)
b = a.numpy()
print(a, b)
(2)NumPy数组转Tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
print(a, b)
(3)NumPy数组转Tensor:数据拷贝
import numpy as np
a = np.ones(5)
c = torch.tensor(a)
print(a, c)
(4)将Tensor在CPU和GPU(需要硬件支持)之间相互移动
# 以下代码只有在PyTorch GPU版本上才会执行
if torch.cuda.is_available():
device = torch.device("cuda") # GPU
y = torch.ones_like(x, device=device) # 直接创建一个在GPU上的Tensor
#【1】把 x从CPU移动到GPU
x = x.to(device)# 等价于 .to("cuda")
z = x + y
print(z)
#【2】把 z从GPU移动到CPU
print(z.to("cpu", torch.double))