Tensor
数据类型
- data :
- dtype :
- shape :
- device :
张量所在设备,GPU / CPU,是加速的关键 - requires_grad :
- grad :
- grad_fn :
- is_leaf :
创建方式
torch.tensor() : 直接创建
torch.tensor( # 从data创建tensor
data, # data : 可以是list,numpy
dtype = None, # 数据类型,默认与data一致
device = None, # 所在设备
requires_grad = False, # 是否需要梯度
pin_memory = False # 是否存于锁页内存
)
从数据创建
torch.from_numpy(ndarry) # 从numpy创建tensor
注意 : 从torch.from_numpy(ndarry)创建的tensor与原ndarray共享内存
torch.rand: (0, 1)均匀分布创建
torch.randn: 标准正态分布创建
张量的拼接
torch.cat() : 在已有维度进行拼接
torch.cat( # 在已有维度进行拼接
tensors, # 张量序列
dim # 维度
)
import torch
arr = torch.ones((2, 3))
arr_0 = torch.cat([arr, arr], dim=0)
arr_1 = torch.cat([arr, arr], dim=1)
print("arr:{} shape:{}\narr_0:{} shape:{}\narr_1:{} shape:{}".format(arr, arr.shape, arr_0, arr_0.shape, arr_1, arr_1.shape))
运行上述脚本结果:
F:\Anaconda\envs\pytorch_gpu\python.exe "F:/PyTorch Learning/hello pytorch/hello.py"
arr:tensor([[1., 1., 1.],
[1., 1., 1.]]) shape:torch.Size([2, 3])
arr_0:tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]) shape:torch.Size([4, 3])
arr_1:tensor([[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1.]]) shape:torch.Size([2, 6])
Process finished with exit code 0
torch.stack() : 新建维度进行拼接
torch.stack( # 在已有维度进行拼接
tensors, # 张量序列
dim # 维度
)
import torch
arr = torch.ones((2, 3))
arr_0 = torch.stack([arr, arr], dim=0)
arr_1 = torch.stack([arr, arr], dim=1)
print("arr:{} shape:{}\narr_0:{} shape:{}\narr_1:{} shape:{}".
format(arr, arr.shape, arr_0, arr_0.shape, arr_1, arr_1.shape))
运行上述脚本结果:
F:\Anaconda\envs\pytorch_gpu\python.exe "F:/PyTorch Learning/hello pytorch/hello.py"
arr:tensor([[1., 1., 1.],
[1., 1., 1.]]) shape:torch.Size([2, 3])
arr_0:tensor([[[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.]]]) shape:torch.Size([2, 2, 3])
arr_1:tensor([[[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.]]]) shape:torch.Size([2, 2, 3])
Process finished with exit code 0
张量的切分
torch.chunk() : 按维度dim进行平均切分
torch.chunk(
tensor, # 要切分的张量
chunks, # 平均切的份数
dim # 切分的维度
)
torch.split() : 按维度dim进行切分
torch.split(
tensor, # 要切分的张量
split, # int:按数值进行切分,list:按列表值切分
dim # 切分的维度
)
张量的索引
torch.index_select() : 按索引返回拼接后新的张量
torch.index_select(
tensor,
index, # index_select(): argument 'index' must be Tensor, not list
dim
)
861

被折叠的 条评论
为什么被折叠?



