NumPy Random Arrays: Complete Guide

One way to create random arrays in numpy is by using functions from the numpy.random module. Some commonly used functions include:

  1. numpy.random.rand(d0, d1, …, dn) generates random samples from a uniform distribution with specified dimensions, ranging from 0 to 1.
  2. numpy.random.randn(d0, d1, …, dn) returns random samples from a standard normal distribution with specified dimensions.
  3. numpy.random.randint(low, high=None, size=None, dtype=int) generates random integer samples within a specified range. The low parameter represents the lower bound (inclusive) and high is the upper bound (exclusive).
  4. numpy.random.random_sample(size=None) returns random sample values between 0 and 1, with the option to specify the number of samples to return using the size parameter.
  5. numpy.random.choice(a, size=None, replace=True, p=None): Select random sample values from a given one-dimensional array ‘a’.

Example code:

import numpy as np

# 生成一个3x3的随机数组(均匀分布)
rand_array = np.random.rand(3, 3)
print(rand_array)

# 生成一个标准正态分布的随机数组(3行2列)
randn_array = np.random.randn(3, 2)
print(randn_array)

# 生成一个10个元素的随机整数数组(取值范围在[0, 10)之间)
randint_array = np.random.randint(0, 10, size=10)
print(randint_array)

# 生成5个[0, 1)之间的随机样本值
random_sample = np.random.random_sample(5)
print(random_sample)

# 从给定的一维数组中随机选择3个样本值
choices = np.random.choice([1, 2, 3, 4, 5], size=3)
print(choices)

The specific use of these functions can be chosen according to needs. For more detailed usage, please refer to the official numpy documentation.

bannerAds