如何用Numpy生成元素对应指定均值方差的正态分布矩阵?求一行代码方案
Hey there! Let's tackle your NumPy questions one by one, nice and straightforward:
1. How to create a normal distribution matrix where each element has a specified mean and variance in NumPy?
If you want all elements to follow the same normal distribution (single mean and variance), it's super simple—just use numpy.random.normal() directly:
import numpy as np # For a 3x3 matrix with mean=5 and variance=2 (so std_dev=√2) matrix = np.random.normal(loc=5, scale=np.sqrt(2), size=(3, 3))
But if you need each element to have its own unique mean and variance, you'll leverage NumPy's broadcasting. Here's how:
- Start with a standard normal distribution (mean=0, std=1) of the same shape as your target matrix.
- Scale each element by the square root of its variance (since
scaleinnormal()expects standard deviation, not variance). - Shift each element by its corresponding mean.
The code would look like this:
# Example: mean and variance are 2D matrices of the same shape mean_matrix = np.array([[1, 2], [3, 4]]) variance_matrix = np.array([[0.5, 1], [1.5, 2]]) sample_matrix = np.random.normal(0, 1, size=mean_matrix.shape) * np.sqrt(variance_matrix) + mean_matrix
2. Can we do this in one line with three same-dimension matrices Mean, Variance, Sample?
Absolutely! NumPy's random.normal() allows loc (mean) and scale (standard deviation) parameters to accept arrays of the same shape as the output. So you can directly pass your Mean matrix as loc, and the square root of Variance as scale. Here's the one-liner:
Sample = np.random.normal(loc=Mean, scale=np.sqrt(Variance))
This will generate each Sample[i,j] to follow a normal distribution with mean Mean[i,j] and variance Variance[i,j] automatically, thanks to NumPy's broadcasting magic. Just make sure Mean and Variance have the exact same shape—no mismatches allowed!
内容的提问来源于stack exchange,提问作者user3639557

