x = torch.empty(5, 3)2)随机初始化Tensor
x = torch.rand(5, 3)3)long型全0的Tensor
x = torch.zeros(5, 3, dtype=torch.long)4)根据数据创建Tensor
x = torch.tensor([5.5, 3])
| 函数 | 功能 |
|---|---|
| tensor(*sizes) | 基础构造函数 |
| tensor(data,) | 类似np.array的构造函数 |
| ones(*sizes) | 全1Tensor |
| zeros(*sizes) | 全0Tensor |
| eye(*sizes) | 对角线为1,其他为0 |
| arange(s,e,step) | 从s到e,步长为step |
| linspace(s,e,steps) | 从s到e,均匀切分成steps份 |
| rand/randn(*sizes) | 均匀/标准分布 |
| normal(mean,std)/uniform(from,to) | 正态分布/均匀分布 |
| randperm(m) | 随机排列 |
加法形式一:
print(x+y)
加法形式二:
print(torch.add(x, y))
加法形式三:
# adds x to y y.add_(x) print(y)2)索引
索引出来的结果与原数据共享内存,也即修改一个,另一个会跟着修改。
y = x[0, :] y += 1 print(y) print(x[0, :]) # 源tensor也被改了 >> tensor([1.6035, 1.8110, 0.9549]) >> tensor([1.6035, 1.8110, 0.9549])
除了常用的索引选择数据之外,PyTorch还提供了一些高级的选择函数:
| 函数 | 功能 |
|---|---|
| index_select(input, dim, index) | 在指定维度dim上选取,比如选取某些行、某些列 |
| masked_select(input, mask) | 使用ByteTensor进行选取 |
| nonzero(input) | 非0元素的下标 |
| gather(input, dim, index) | 根据index,在dim维度上选取数据,输出的size与index一样 |
用view()来改变Tensor的形状:注意view()返回的新Tensor与源Tensor虽然可能有不同的size,但是是共享data的,也即更改其中的一个,另外一个也会跟着改变。
y = x.view(15) z = x.view(-1, 5) # -1所指的维度可以根据其他维度的值推出来 print(x.size(), y.size(), z.size()) >> torch.Size([5, 3]) torch.Size([15]) torch.Size([3, 5])方法二:clone().view()
如果想返回一个不共享data内存的副本,推荐先用clone创造一个副本然后再使用view。
x_cp = x.clone().view(15)
x -= 1
print(x)
print(x_cp)
>> tensor([[ 0.6035, 0.8110, -0.0451],
[ 0.8797, 1.0482, -0.0445],
[-0.7229, 2.8663, -0.5655],
[ 0.1604, -0.0254, 1.0739],
[ 2.2628, -0.9175, -0.2251]])
>> tensor([1.6035, 1.8110, 0.9549, 1.8797, 2.0482, 0.9555, 0.2771, 3.8663, 0.4345,
1.1604, 0.9746, 2.0739, 3.2628, 0.0825, 0.7749])
4.线性代数
另外,PyTorch还支持一些线性函数:
| 函数 | 功能 |
|---|---|
| trace | 对角线元素之和(矩阵的迹) |
| diag | 对角线元素 |
| triu/tril | 矩阵的上三角/下三角,可指定偏移量 |
| mm/bmm | 矩阵乘法,batch的矩阵乘法 |
| t | 转置 |
| dot/cross | 内积/外积 |
| inverse | 求逆矩阵 |
| svd | 奇异值分解 |
当对两个形状不同的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]])
6.运算的内存开销
# 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 # 如果想指定结果到原来的y的内存,我们可以使用前面介绍的索引来进行替换操作 x = torch.tensor([1, 2]) y = torch.tensor([3, 4]) id_before = id(y) y[:] = y + x print(id(y) == id_before) # True7.Tensor和NumPy相互转换
用numpy()和from_numpy()将Tensor和NumPy中的数组相互转换。但这两个函数所产生的的Tensor和NumPy中的数组共享相同的内存,改变其中一个时另一个也会改变。另一个常用的将NumPy中的array转换成Tensor的方法就是torch.tensor(), 此方法总是会进行数据拷贝(就会消耗更多的时间和空间),所以返回的Tensor和原来的数据不再共享内存。
1)Tensor转NumPy使用numpy()将Tensor转换成NumPy数组:
a = torch.ones(5) b = a.numpy() print(a, b) a += 1 print(a, b) b += 1 print(a, b) >> tensor([1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1.] >> tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.] >> tensor([3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3.]2) NumPy数组转Tensor
使用from_numpy()将NumPy数组转换成Tensor:
import numpy as np a = np.ones(5) b = torch.from_numpy(a) print(a, b) a += 1 print(a, b) b += 1 print(a, b) >> [1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64) >> [2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2.], dtype=torch.float64) >> [3. 3. 3. 3. 3.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)3)torch.tensor()
直接用torch.tensor()将NumPy数组转换成Tensor,该方法总是会进行数据拷贝,返回的Tensor和原来的数据不再共享内存。
import numpy as np a = np.ones(5) c = torch.tensor(a) a += 1 print(a, c) >> [4. 4. 4. 4. 4.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)8.Tensor on GPU
用方法to()可以将Tensor在CPU和GPU(需要硬件支持)之间相互移动。
# 以下代码只有在PyTorch GPU版本上才会执行
if torch.cuda.is_available():
device = torch.device("cuda") # GPU
y = torch.ones_like(x, device=device) # 直接创建一个在GPU上的Tensor
x = x.to(device) # 等价于 .to("cuda")
z = x + y
print(z)
print(z.to("cpu", torch.double)) # to()还可以同时更改数据类型



