Tensor的创建

Import from numpy

a = np.array([2, 3.3])
b = torch.from_numpy(a)

a = np.ones([2, 3])
b = torch.from_numpy(a)

Import from list

# 接受data
torch.tensor([2., 3.2])         
torch.FloatTensor([2., 3.2])   
# 接受shape
torch.FloatTensor(2, 3)   # 记得初始化!

rand/rand_like/randint/randn/normal

# [0,1)
torch.rand(3, 3)

a = torch.rand(3, 3)
torch.rand_like(a)

# [min,max)
torch.randint(1, 10, [3, 3])

# 正态分布N(u,std)    默认N(0,1)  
# 对每个值,按照其对应位置的means、std,在N(means,std)随机
# 传参只能是一维向量  还需要reshape
# out 指定输出到某个tensor中
torch.randn(3, 3)
torch.normal(means = torch.full([10], 0), std = torch.arange(1, 0, -0.1), out = a)

full

torch.full([2, 3], 19260817)
# 要创建scalar  括号里不要填
torch.full([], 19260817)

arange

# [min,max)
torch.arnage(0, 10, 2)
# tensor([0, 2, 4, 6, 8])

linspace/logspace

# [min,max] 数量(不是步长)
torch.linspace(0, 10, steps = 4)
# 10^ ([min,max])
torch.logspace(0, -1, steps = 10)
# tensor([1.000, 0.7743, ... , 0.1000])

ones/zeros/eye

# ones  全1
torch.ones(3, 3, 2)
# zeros 全0
# eye 对角线为1
torch.eye(3, 4)

randperm

# 生成随机排列
torch.randperm(10)

可以利用这个操作实现 random_shuffle :

a = torch.rand(10, 2)
idx = torch.randperm(10)

for i in range(idx)
	a[idx]...
posted @ 2022-03-29 16:27  YoungNeal  阅读(194)  评论(0编辑  收藏  举报