from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import torch
a = torch.Tensor([[1,2,3],[4,5,6]])
a
tensor([[1., 2., 3.],
[4., 5., 6.]])
a = torch.Tensor(2,3)
a
tensor([[2.1252e-07, 4.2052e-05, 2.6608e+23],
[1.3178e-08, 1.6705e+22, 2.1067e-07]])
# 利用torch.Tensor,可以直接将数据转化tensor张量也可以通过指定形状”随机“生成
b = torch.ones(3,4)
b
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
b = torch.zeros(3,2)
b
tensor([[0., 0.],
[0., 0.],
[0., 0.]])
b = torch.eye(3,4)
b
tensor([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.]])
c = torch.zeros_like(b)
c
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
c = torch.ones_like(a)
c
tensor([[1., 1., 1.],
[1., 1., 1.]])
# 可以利用ones,zeros,eye生成指定形状的和内容的特殊张量,ones-全1;zeros-全0;eye-对角线为1;也可以使用one_like生成给定张量形状的特殊类型张量
# 随机
d = torch.rand(2,3)
d
tensor([[0.6153, 0.0431, 0.0203],
[0.7537, 0.7745, 0.1998]])
# 生成0-1之间随机值
d = torch.normal(mean=1,std=0.5,size=(2,3))
d
tensor([[0.5167, 1.1842, 1.9300],
[0.1088, 0.6602, 0.9518]])
# 根据给的的均值和标准差在相应的正态分布中取随机值
e = torch.normal(mean=1,std=torch.ones(3,3))
e
tensor([[1.4304, 1.1978, 0.4406],
[0.8869, 0.0687, 1.6330],
[0.3296, 0.0228, 1.5804]])
# 根据给定的标准差,对应位置给定的标准差和均值构造正态分布,然后取值
f = torch.normal(mean = e,std=1)
f
tensor([[ 2.4143, 1.0414, 1.6535],
[-0.6699, -0.3875, 0.8023],
[-0.8736, 1.2619, 2.2611]])
# 同上
# normal可用于参数初始化,或随机生成值
torch.ones(3,4).uniform_(-1,1)
tensor([[ 0.0271, 0.5928, 0.1228, -0.3689],
[-0.2387, -0.3837, -0.3248, -0.5375],
[ 0.0277, -0.4428, -0.9850, -0.2784]])
# 均匀分布,指定tensor形状,均匀采样
# 序列
torch.arange(0,10,1)
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
torch.arange(0,10,1).reshape(2,5)
tensor([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
# 顺序序列,步长为1,步长可修改,类型为LongTensor
torch.linspace(2,10,3)
tensor([ 2., 6., 10.])
# 等间隔取值
torch.randperm(10)
tensor([9, 6, 0, 8, 5, 2, 7, 1, 3, 4])
# 生成从0-m随机序列,类型为LongTensor