pytorch对tensor的一些基本操作(一)

Tensor张量

import torch
x=torch.Tensor(5)#默认为0
print(x)
tensor([0., 0., 0., 0., 0.])

1.torch.ones默认值为1

x=torch.ones(1,2)
print(x)
tensor([[1., 1.]])

2.torch.zeros默认值为0

x=torch.zeros(1,2)
print(x)
tensor([[0., 0.]])

3.torch.full填充

x=torch.full((1,2),3.14)
print(x)
tensor([[3.1400, 3.1400]])

4.torch.empty为空

x=torch.empty(3,4)
print(x)
tensor([[-9.9029e+20,  4.5825e-41, -1.2786e-34,  3.0943e-41],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00]])

5.torch.rand随机数,均匀分布在0和1之间

x=torch.rand(3,4)
print(x)
tensor([[0.3000, 0.7942, 0.1237, 0.6727],
        [0.9596, 0.7241, 0.0643, 0.2116],
        [0.9158, 0.6850, 0.3265, 0.1381]])

6.torch.randn正态分布,均值为0,方差为1

x=torch.randn(3,4)
print(x)
tensor([[ 1.3331,  0.7957, -0.5624, -1.1328],
        [ 0.4470,  1.2949, -0.2512,  1.8618],
        [ 0.6336, -0.6330,  0.9996, -1.2672]])

7.torch.randint创建随机整数

x=torch.randint(1,99,(3,4))#需要给出范围及tensor的大小
print(x)
tensor([[97, 82, 88, 67],
        [23, 35, 32, 70],
        [61, 50, 90, 44]])

8.torch.randperm选择随机数,下面的例子为输出0到99的100个随机数

x=torch.randperm(99)#需要给出范围
print(x)
tensor([84, 47, 66, 85, 44, 72, 69, 41,  3, 18, 70, 81, 76, 95,  4, 90, 25, 22,
        71, 93, 42, 33, 34, 89, 56, 64, 32, 28, 17, 36, 80, 15, 87, 82, 29,  0,
        77, 19,  1, 60, 31,  6, 73, 88, 78, 12, 27, 49,  5, 43, 11, 40, 45, 96,
         8, 75, 26, 24, 37, 65, 74, 52, 10, 97, 39, 20, 58, 92, 98, 83, 50, 21,
        59,  7, 61, 46,  9, 91, 23, 62, 55, 53, 67, 79,  2, 57, 51, 63, 14, 86,
        94, 13, 30, 68, 16, 38, 54, 35, 48])

9.torch.argmin() 特别的在dim=0表示二维中的列,dim=1在二维矩阵中表示行

x = torch.randint(1,99,(3,3))
print(x)
print(torch.argmin(x, dim=0))#返回每列的最小值的索引
tensor([[66, 89, 26],
        [72, 48, 86],
        [ 4, 62, 80]])
tensor([2, 1, 0])

10.torch.argmax() 同理

x = torch.randint(1,99,(3,3))
print(x)
print(torch.argmax(x, dim=1))#返回每行的最大值的索引

                
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值