1.数据操作
为什么要用tensor?
答:Tensor提供GPU计算和自动求梯度等更多功能,这些使Tensor相比于numpy更加适合深度学习。
1.1 创建tensor的方式
1.用tenor.empty()创建未初始化的tensor
x = torch.empty(5, 3)
print(x)
2.用tensor.rand()创建随机初始化的tensor
x = torch.rand(5, 3)
print(x)
3.用tensor.zeros()创建全为0的tensor
x = torch.zeros(5, 3)
print(x)
4.用torch.tensor()直接根据数据创建tensor
x = torch.tensor([5.5, 3])
print(x)
5.用torch.tensor.new_ones()或者torch.randn_like()借助已有tensor创建新tensor
x = torch.tensor([5.5, 3])
x = x.new_ones(5, 3, dtype=torch.float64) # 返回的tensor默认具有相同的torch.dtype和torch.device
print(x)
x = torch.randn_like(x, dtype=torch.float) # 指定新的数据类型
print(x)
可以用torch.tensor.size()或者torch.tensor.shape查看tensor形状
print(x.size())
print(x.shape)
1.2 操作tensor
1.算数操作
加法操作1
x = torch.rand(5, 3)
y = torch.rand(5, 3)
print(x + y)
加法操作2
x = torch.rand(5, 3)
y = torch.rand(5, 3)
print(torch.add(x, y))
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
加法操作3
x = torch.rand(5, 3)
y = torch.rand(5, 3)
y.add_(x)
print(y)
2.索引
我们还可以使用类似NumPy的索引操作来访问Tensor的一部分,需要注意的是:索引出来的结果与原数据共享内存,也即修改一个,另一个会跟着修改。
x = tensor.rand(5,3)
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])
3.改变tensor形状
torch.tensor.view()改变tensor的形状
x = tensor.rand(5,3)
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])
注意view()返回的新Tensor与源Tensor虽然可能有不同的size,但是是共享data的,也即更改其中的一个,另外一个也会跟着改变。
x += 1
print(x)
print(y) # 也加了1
如果不想这样可以用torch.tensor.clone.view()
x_cp = x.clone().view(15)
x -= 1
print(x)
print(x_cp) #此时输出不同
torch.tensor.item()可以将一个标量Tensor转换成一个Python number
x = torch.randn(1)
print(x)
print(x.item())
tensor([2.3466])
2.3466382026672363
1.3 广播机制
当对两个形状不同的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]])
1.4 Tensor和NumPy相互转换
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)
- 这两个函数所产生的的Tensor和NumPy中的数组共享相同的内存(所以他们之间的转换很快),改变其中一个时另一个也会改变。
- 还有一个常用的将NumPy中的array转换成Tensor的方法就是torch.tensor(), 需要注意的是,此方法总是会进行数据拷贝(就会消耗更多的时间和空间),所以返回的Tensor和原来的数据不再共享内存。
1.5 Tensor on GPU
用方法to()可以将Tensor在CPU和GPU(需要硬件支持)之间相互移动。
# 以下代码只有在PyTorch GPU版本上才会执行
x = torch.rand(5,3)
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()还可以同时更改数据类型