如何生成一个二维数组,其元素在轴=0 处为均匀随机数,在轴=1 处为正态随机数

问题描述

我正在尝试使用 numpy 或 scipy 生成二维数组,例如 (10000,1024)。我希望这个数组每一行的元素都满足正态分布。但是,每一列的元素都是统一的随机数。

我不知道如何实现这个目标。任何帮助将不胜感激。

谢谢。

解决方法

列上的“完美”均匀分布和行上的正态分布(如果您谈论的是随机变量矩阵)。

但如果尺度(标准差)不太宽,您可以组合 sps.normsps.uniform,以便位置(均值)和尺度可以足够均匀地按行分布。

例如

# imports
import numpy as np
import scipy.stats as sps
import seaborn as sns
import matplotlib.pyplot as plt

# define rows and columns
# define rows and columns
rows = 10000
cols = 1024
# generate random samples
matrix = sps.norm(
    # uniformly distributed locations
    loc=sps.uniform(0,200).rvs(rows).reshape(-1,1),# uniformly distributed scales
    scale=sps.uniform(1,5).rvs(rows).reshape(-1,).rvs((rows,cols))

你可以验证所有的行都是正态分布的

fig,ax = plt.subplots(2,4,figsize=(15,8))
# take some random test rows
test_rows = np.random.choice(rows,size=8)
# plot rows histplots
for i,row in enumerate(test_rows):
    sns.histplot(matrix[row,:].ravel(),ax=ax.flat[i])
    ax.flat[i].set(
        ylabel=None,title=f'row {row}'
    )

enter image description here

和列非常类似于均匀分布

fig,8))
# take some random test columns
test_cols = np.random.choice(cols,size=8)
# plot columns histplots
for i,col in enumerate(test_cols):
    sns.histplot(matrix[:,col].ravel(),title=f'column {col}'
    )

enter image description here

但标准差越高,越多的列会从均匀分布向正态分布本身偏离。