Pytorch中,torch.Tensor(张量)是存储和变换数据的主要工具。Tensor和NumPy.Array很类似。但是Tensor提供GPU计算和自动求梯度等更多功能,使Tensor更加适合深度学习。torch.Tensor的官方文档:https://pytorch.org/docs/stable/tensors.html
创建Tensor的Pytorch实现方式:
1)随机初始化创建
import torch
x=torch.rand(2,3)#创建一个两行三列的二维张量
print(x)
#常用:rand/randn(sizes) rand是[0,1)均匀分布; randn是服从N(0,1)的正态分布
#normal(mean,std)是均值为mean,标准差是std的正态分布
2)全0/1创建
import torch
x = torch.zeros(2, 3) #全零创建
y = torch.ones(2, 3) #全1创建
3)使用现有数据创建
#在cmd Python中运行
import torch
torch.tensor([1, 2, 3, 4])
#output:tensor([1, 2, 3, 4])
想要查看tensor的形状,可以使用x.size()或者x.shape。 (x为现有的tensor)
张量的操作:
1)张量的加法
import torch
# 法1
x = torch.rand(4, 3)
y = torch.rand(4, 3)
print(x + y)
# 法2
print(torch.add(x, y))
# 法3
y.add_(x)
print(y)
2)张量的索引操作
import torch
x=torch.rand(2,3)
print(x)
#tensor([[0.7650, 0.3284, 0.7763],[0.8035, 0.8384, 0.6750]])
x[0,1]=0.5
print(x)
#tensor([[0.7650, 0.5000, 0.7763],[0.8035, 0.8384, 0.6750]])
x[0,:]#打印第一行
#tensor([0.7650, 0.5000, 0.7763])
3)维度的变换
torch.view()和torch.reshape()方法均可以用来做维度的变换,但是:
torch.view(): 这个函数返回的新张量与源张量共享数据,如果你改变其中一个,另一个也会改变。
torch.reshape():因为此函数并不能保证返回的是其拷贝值,所以官方不推荐使用。(返回结果可能是一个拷贝,也可能是源张量的一个视图(view)。这取决于在执行操作时是否需要在内存中对源张量进行重新排列(源张量在内存中不连续)。)
(懒得敲了 贴个图吧)
注意: 改变形状的操作不能改变张量的元素总数。
import torch
x = torch.randn(3, 4)
print(x)
#tensor([[-0.2427, -0.7801, -0.4966, 2.1824],[ 0.8641, -0.3924, 0.0935, 1.6579],
#[-1.0614, -1.9680, 1.1032, 1.1881]])
# 使用 view() 改变张量形状
y = x.view(2, 6)
print(y)
#tensor([[-0.2427, -0.7801, -0.4966, 2.1824, 0.8641, -0.3924],
#[ 0.0935, 1.6579, -1.0614, -1.9680, 1.1032, 1.1881]])
# 使用 reshape() 改变张量形状
z = x.reshape(-1, 2) # -1是指这一维的维数由其他维度决定
print(z)
#tensor([[ 0.7573, 0.2199], [ 0.5034, 3.1824], [ 1.8641, 0.6076],
#[ 1.0935, 2.6579], [-0.0614, -0.9680], [ 2.1032, 2.1881]])
4)广播机制
当对两个形状不同的 Tensor 按元素运算时,可能会触发广播(broadcasting)机制:先适当复制元素使这两个 Tensor 形状相同后再按元素运算。一般来说是复制n次一整行或者n次一整列。
x=torch.arange(1,3) # x=tensor([1, 2])
y=torch,arange(1,4).view(3,1) # y=tensor([[1], [2], [3]])
print(x+y)
#tensor([[2, 3], [3, 4], [4, 5]])