#torch.rand() #torch.randn() #torch.randint() #torch.randperm()用法

示例代码:

import torch

# 生成一个形状为(3, 4)的张量,元素值在[0, 1)之间
tensor = torch.rand((3, 4))
print(tensor)
1
2
3
4
5
输出:

tensor([[0.1490, 0.7928, 0.0411, 0.5075],
        [0.0754, 0.8043, 0.7533, 0.1298],
        [0.5087, 0.1185, 0.6706, 0.9509]])

进程已结束,退出代码0
1
2
3
4
5

torch.randn()
  torch.randn()函数用于生成具有标准正态分布的随机数,即均值为0,标准差为1的随机数。它同样接受一个形状参数,并返回一个指定形状的张量。

示例代码:

import torch

# 生成一个形状为(3, 4)的张量,元素值服从标准正态分布
tensor = torch.randn((3, 4))
print(tensor)
print("均值:", tensor.mean().item())
print("标准差:", tensor.std().item())
1
2
3
4
5
6
7
输出:

tensor([[ 1.7490, -0.1910, -0.6926,  0.2398],
        [ 0.9135, -0.3359,  1.0442,  0.7824],
        [-0.7138,  0.1682, -1.2245, -0.3747]])
均值: 0.1137121245265007
标准差: 0.868906557559967

进程已结束,退出代码0
1
2
3
4
5
6
7


torch.randint()
  torch.randint()函数用于生成指定范围内的整数随机数。它接受三个参数:low(最小值)、high(最大值)和形状(shape)。返回的张量中的元素值将在**[low, high)**范围内。

示例代码:

import torch

# 生成一个形状为(3, 4)的张量,元素值在[0, 10)之间
tensor = torch.randint(0, 10, (3, 4))
print(tensor)
1
2
3
4
5
输出:

tensor([[4, 0, 8, 4],
        [0, 9, 4, 3],
        [0, 3, 9, 3]])

进程已结束,退出代码0
1
2
3
4
5


torch.randperm()
  torch.randperm()函数用于生成一个从0到n-1的随机整数排列。它接受一个参数n,返回一个长度为n的张量,其中包含从0到n-1的随机整数,每个整数只出现一次。

示例代码:

import torch

# 生成一个长度为10的随机整数排列
tensor = torch.randperm(10)
print(tensor)
1
2
3
4
5
输出:

tensor([0, 7, 1, 2, 9, 6, 3, 5, 4, 8])

进程已结束,退出代码0
1
2
3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值