?
import torch
import numpy
torch.manual_seed(7) # 固定随机数种子
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创建的tensor于原ndarray共享内存,当修改其中一个数据,另一个也将会被改动。
a = numpy.array([1, 2, 3])
t = torch.from_numpy(a)
torch.zeros(2, 3)
tensor([[0., 0., 0.],
, [0., 0., 0.]])
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.]])
input = torch.empty(2, 3)
torch.ones_like(input)
tensor([[1., 1., 1.],
, [1., 1., 1.]])
?
torch.arange(1, 2.5, 0.5)
tensor([1.0000, 1.5000, 2.0000])
?
torch.normal(mean, std, out=None) : 生成正态分布
# mean为张量, std为张量
torch.normal(mean=torch.arange(1., 11.), std=torch.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, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) : 生成标准正态分布
?
torch.randn(2, 3)
tensor([[1.3955, 1.3470, 2.4382],
, [0.2028, 2.4505, 2.0256]])
?
torch.rand(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) :?在[0,1)上,生成均匀分布。
torch.rand(2, 3)
tensor([[0.7405, 0.2529, 0.2332],
, [0.9314, 0.9575, 0.5575]])
torch.cat(tensors, dim=0, out=None) :?将张量按维度进行拼接
?
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, dim=0, out=None) :?在新创建的维度上进行拼接
torch.chunk(input, chunks, dim=0)? :?将张量按维度进行平均切分