网上购物都有哪些网站,wordpress 发布vr,公司做网络推广怎么做,营销型网站建设价格是多少张量的创建
张量#xff08;Tensors#xff09;类似于NumPy的ndarrays #xff0c;但张量可以在GPU上进行计算。从本质上来说#xff0c;PyTorch是一个处理张量的库。一个张量是一个数字、向量、矩阵或任何n维数组。 import torch
import numpy
torch.manual_seed(7) # 固…张量的创建
张量Tensors类似于NumPy的ndarrays 但张量可以在GPU上进行计算。从本质上来说PyTorch是一个处理张量的库。一个张量是一个数字、向量、矩阵或任何n维数组。 import torch
import numpy
torch.manual_seed(7) # 固定随机数种子
直接创建
torch.tensor(data, dtypeNone, deviceNone, requires_gradFalse, pin_memoryFalse)功能从data创建tensor data: 数据可以是listnumpydtype: 数据类型默认与data的一致device: 所在设备cuda/cpurequires_grad: 是否需要梯度pin_memory: 是否存于锁页内存
torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])tensor([[0.1000, 1.2000],
, [2.2000, 3.1000],
, [4.9000, 5.2000]])
torch.from_numpy(ndarray)功能从numpy创建tensor
从torch.from_numpy创建的tensor于原ndarray共享内存当修改其中一个数据另一个也将会被改动。
a numpy.array([1, 2, 3])
t torch.from_numpy(a) 依据数值创建¶
torch.zeros(*size, outNone, dtypeNone, layouttorch.strided, deviceNone, requires_gradFalse)功能依size创建全0张量 size: 张量的形状out: 输出的张量layout: 内存中布局形式device: 所在设备requires_grad: 是否需要梯度
torch.zeros(2, 3)tensor([[0., 0., 0.],
, [0., 0., 0.]])
torch.zeros_like(input, dtypeNone, layoutNone, deviceNone, requires_gradFalse)功能依input形状创建全0张量 input: 创建与input同形状的全0张量dtype: 数据类型layout: 内存中布局形式
input torch.empty(2, 3)
torch.zeros_like(input)tensor([[0., 0., 0.],
, [0., 0., 0.]])
torch.ones(2, 3)tensor([[1., 1., 1.],
, [1., 1., 1.]])
torch.ones_like(input, dtypeNone, layoutNone, deviceNone, requires_gradFalse)功能依input形状创建全1张量 size: 张量的形状dtype: 数据类型layout: 内存中布局形式device: 所在设备requires_grad: 是否需要梯度
input torch.empty(2, 3)
torch.ones_like(input)tensor([[1., 1., 1.],
, [1., 1., 1.]]) torch.full_like(input, dtypeNone, layouttorch.strided, deviceNone, requires_gradFalse)功能: 依input形状创建指定数据的张量 size: 张量的形状fill_value: 张量的值torch.arange(start0, end. step1, outNone, dtypeNone, layouttorch.strided, deviceNone, requires_gradFalse)功能创建等差的1维张量 start: 数列起始值end: 数列结束值step: 数列公差默认为1
torch.arange(1, 2.5, 0.5)tensor([1.0000, 1.5000, 2.0000]) 依概率分布创建张量
torch.normal(mean, std, outNone) : 生成正态分布
# mean为张量, std为张量
torch.normal(meantorch.arange(1., 11.), stdtorch.arange(1, 0, -0.1))tensor([0.8532, 2.7075, 3.7575, 3.2200, 6.0145, 5.5526, 6.8577, 8.3697, 9.0276,
, 9.8318]) torch.randn(*size, outNone, dtypeNone, layouttorch.strided, deviceNone, requires_gradFalse) : 生成标准正态分布 torch.randn(2, 3)tensor([[1.3955, 1.3470, 2.4382],
, [0.2028, 2.4505, 2.0256]]) torch.rand(*size, outNone, dtypeNone, layouttorch.strided, deviceNone, requires_gradFalse) : 在[0,1)上生成均匀分布。
torch.rand(2, 3)tensor([[0.7405, 0.2529, 0.2332],
, [0.9314, 0.9575, 0.5575]]) 张量拼接与切分
torch.cat(tensors, dim0, outNone) : 将张量按维度进行拼接 x torch.randn(2, 3)
torch.cat((x, x, x), 1)#
tensor([[-1.7038, 0.6248, 0.1196, -1.7038, 0.6248, 0.1196, -1.7038, 0.6248,
, 0.1196],
, [-0.8049, 1.6162, 0.2516, -0.8049, 1.6162, 0.2516, -0.8049, 1.6162,
, 0.2516]]) torch.stack(tensors, dim0, outNone) : 在新创建的维度上进行拼接 torch.chunk(input, chunks, dim0) : 将张量按维度进行平均切分