NumPy中的random模块可以用来生成随机数或数组。以下是一些常用的随机数组生成函数:

  1. np.random.rand(d0, d1, ..., dn):生成一个指定形状的数组,数组元素在[0,1)之间均匀分布。

  2. np.random.randn(d0, d1, ..., dn):生成一个指定形状的数组,数组元素服从标准正态分布(平均值为0,方差为1)。

  3. np.random.randint(low, high=None, size=None, dtype='l'):生成一个指定形状的数组,数组元素在指定区间内随机生成整数。

  4. np.random.random_sample(size=None):生成一个指定形状的数组,数组元素在[0,1)之间均匀分布。

  5. np.random.choice(a, size=None, replace=True, p=None):从一个指定的一维数组中生成随机数或随机数组。

  6. np.random.shuffle(x):将一个数组随机打乱顺序。

  7. np.random.permutation(x):返回一个随机排列的数组。

示例:

import numpy as np

# 生成一个3x3的随机数组,元素在[0,1)之间均匀分布
arr1 = np.random.rand(3, 3)
print(arr1)

# 生成一个3x3的随机数组,元素服从标准正态分布
arr2 = np.random.randn(3, 3)
print(arr2)

# 生成一个3x3的随机数组,元素在[0,10)之间随机生成整数
arr3 = np.random.randint(0, 10, size=(3, 3))
print(arr3)

# 生成一个3x3的随机数组,元素在[0,1)之间均匀分布
arr4 = np.random.random_sample((3, 3))
print(arr4)

# 从数组[1, 2, 3, 4, 5]中随机选择3个数
arr5 = np.random.choice([1, 2, 3, 4, 5], size=3, replace=False)
print(arr5)

# 将数组[1, 2, 3, 4, 5]随机打乱顺序
arr6 = np.array([1, 2, 3, 4, 5])
np.random.shuffle(arr6)
print(arr6)

# 返回一个随机排列的数组[1, 2, 3, 4, 5]
arr7 = np.random.permutation([1, 2, 3, 4, 5])
print(arr7)
numpy随机生成数组

原文地址: http://www.cveoy.top/t/topic/bCol 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录