Pytorch学习笔记【2】 --创建tensor的N种姿势

Pytorch学习笔记【2】 --创建tensor的N种姿势

Pytorch笔记目录:点位进入

从Numpy中导入

Pytorch可以把numpy的数据类型直接转化为tensor类型
torch.from_numpy(a)

# Import form numpy
a  = np.array([2,3.3])
b = torch.from_numpy(a)
print(b)
a =  np.ones([2,3])
print(torch.from_numpy(a))

out:
tensor([2.0000, 3.3000], dtype=torch.float64)
tensor([[1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)

从List类型转换

# Import from List
print(torch.tensor([2,3.3]))
print(torch.tensor([2,3.3]))

out:
tensor([2.0000, 3.3000])

rand—0-1之间的随机数

torch.rand()
args: 填入维度即可

# rand/rand_like, randint
a = torch.rand(3,3)
print(a)
out:tensor([[0.3825, 0.1597, 0.3527],
        [0.0256, 0.2336, 0.1741],
        [0.6647, 0.6769, 0.0657]])rand

torch.rand_like

print(torch.rand_like(a))
out:
tensor([[0.1660, 0.3385, 0.6624],
            [0.3593, 0.5983, 0.8386],
            [0.9682, 0.8471, 0.6832]])

torch.randint()

torch.randint()
args: 前两个是生成随机数的范围

print(torch.randint(1,10,[3,4]))
out:
tensor([[8, 7, 9, 8],
            [2, 6, 4, 6],
            [3, 1, 5, 8]])

torch.randn()

生成-1,1之间的随机数
args: 生成tensor的维度

print(torch.randn(3,3))
out:
tensor([[ 0.0789,  0.4458, -0.7294],
            [ 0.6613, -0.7764,  0.4426],
            [-1.3602, -0.9148,  2.3069]])

torch.full()

说明:用某个数值填满tensor
args:维度,数字

print(torch.full([2,3],7))
out:
tensor([[7., 7., 7.],
            [7., 7., 7.]])

torch.normal()

将tensor用均值为mean和标准差为std的正态分布填充
args: mean:均值,std:标准差

print(torch.normal(mean=0,std=1)

torch.arrange()

类似于python的arange机制
args:范围和步长

print(torch.arange(0,10))
out:
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

print(torch.arange(0,10,2))
out:
tensor([0, 2, 4, 6, 8])

torch.linspce()

将一定范围内的数值按照补偿进行切割
args:范围,步长

torch.linspace(0,10,steps=4)
out:
tensor([ 0.0000,  3.3333,  6.6667, 10.0000])

torch.ones()

用1来填充tensor
args:维度

torch.ones(3,3)
out:
 tensor([[1., 1., 1.],
            [1., 1., 1.],
            [1., 1., 1.]])

torch.zeros(3,3)

用0来填充tensor
args:维度

torch.zeros(3,3) 
out:
tensor([[0., 0., 0.],
            [0., 0., 0.],
            [0., 0., 0.]])

torch.eye()

创建对角线上都是1的tensor,如果tensor的长宽相等就是一个单位矩阵拉
args: 维度

torch.eye(3,3)
out:
tensor([[1., 0., 0.],
            [0., 1., 0.],
            [0., 0., 1.]])
原创文章 113 获赞 80 访问量 3万+

猜你喜欢

转载自blog.csdn.net/python_LC_nohtyp/article/details/105981108