import torch
import numpy as np
# Import form numpy:使用numpy进行创建
a = np.array([2, 3.3])
print(a) # [2. 3.3]
b = torch.from_numpy(a) # numpy转化为tensor类型
print(b) # tensor([2.0000, 3.3000], dtype=torch.float64)
# Import form List:使用list创建
a = torch.tensor([2, 3.2])
print(a) # tensor([2.0000, 3.2000])
b = torch.FloatTensor([2, 3.2])
print(b) # tensor([2.0000, 3.2000])
c = torch.FloatTensor(2, 3)
print(c)
# uninitialized:根据shape创建Tensor
a = torch.empty(2, 3)
print(a)
b = torch.Tensor(2, 3)
print(b)
c = torch.IntTensor(2, 3)
print(c)
d = torch.FloatTensor(2, 3)
print(d)
# set default type:修改tensor的默认类型
a = torch.tensor([1.2, 3]).type()
print(a) # torch.FloatTensor
torch.set_default_tensor_type(torch.DoubleTensor)
b = torch.tensor([1.2, 3]).type()
print(b) # torch.DoubleTensor
# rand/rand_like, randit
a = torch.rand(3, 3) # 采样自0~1均匀分布
print(a)
b = torch.rand(3, 3)
c = torch.rand_like(b)
print(b)
print(c)
a = torch.randint(1, 10, [3, 3]) # 在区间[1, 10)上随机采样,生成shape=2,2的LongTensor
print(a)
# randn:正态分布
a = torch.randn(3, 3) # 采样自(0, 1)正态分布
print(a)
# full:使用相同元素构建
a = torch.full([2, 3], 7) # shape=2,3, 所使用的相同的元素为7
print(a)
# # arange/range
b = torch.arange(0, 10)
print(b) # tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
c = torch.arange(0, 10, 2)
print(c) # tensor([0, 2, 4, 6, 8])
d = torch.range(0, 10)
print(d)
# linspace/logspace:注意第三个参数为步长
a = torch.linspace(0, 10, steps=4) # 注意:10也可以取到
print(a) # tensor([ 0.0000, 3.3333, 6.6667, 10.0000])
b = torch.linspace(0, 10, steps=10)
print(b) # tensor([ 0.0000, 1.1111, 2.2222, 3.3333, 4.4444, 5.5556, 6.6667, 7.7778,8.8889, 10.0000])
c = torch.linspace(0, 10, steps=11)
print(c) # # tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
# Ones/zeros/eye
a = torch.ones(3, 3) # 全1
print(a)
b = torch.zeros(3, 3) # 全0
print(b)
c = torch.eye(3, 3) # 对角阵
print(c)
d = torch.eye(5) # shape=5,5的对角阵
print(d)
# randperm: random.shuffle
# 两个Tensor的shape[0]是相同的,都是2
a = torch.rand(2, 3)
b = torch.rand(2, 2)
idx = torch.randperm(2) # 制造一个[0,2)的索引序列
print(idx) # 是变化的
print(a[idx])
print(a)
print(b[idx])
print(b)
PyTorch学习2:创建Tensor的多种方法
最新推荐文章于 2024-06-23 10:53:43 发布