Python-根据相关矩阵生成数字

Python-Generating numbers according to a corellation matrix

您好,我正在尝试生成尽可能接近第一个 table 的相关数据(总共 13 行中显示的前三行)。还显示了相关列的相关矩阵 (corr_total)。

我正在尝试以下代码,它显示了错误: "LinAlgError: 4-th leading minor not positive definite"

from scipy.linalg import cholesky

# Correlation matrix

# Compute the (upper) Cholesky decomposition matrix

upper_chol = cholesky(corr_total)

# What should be here? The mu and sigma of one row of a table?
rnd = np.random.normal(2.57, 0.78, size=(10,7))


# Finally, compute the inner product of upper_chol and rnd
ans = rnd @ upper_chol

我的问题是 mu 和 sigma 的值是什么,以及如何解决上面显示的错误。 谢谢! P.S 我已编辑问题以显示原始问题 table。它显示了四名患者的数据。我基本上想为更多病例制作合成数据,以复制在这些患者中发现的模式

感谢您回答我关于何时可以访问数据的问题。您收到的错误是在您调用 cholesky 时生成的。 cholesky 要求您的矩阵是正半定的。检查矩阵是否半正定的一种方法是查看其所有特征值是否都大于零。 correlation/covarance 矩阵的特征值之一几乎为零。我认为 cholesky 只是挑剔。使用可以使用scipy.linalg.sqrtm作为替代分解。

对于您关于生成多元法线的问题,您生成的随机法线应该是标准随机法线,即平均值为 0,宽度为 1。Numpy 提供了一个标准随机法线生成器 np.random.randn. 要生成多元正态分布,您还应该分解协方差,而不是相关矩阵。下面将使用仿射变换生成多元法线,如您的问题。

from scipy.linalg import cholesky, sqrtm
relavant_columns = ['Affecting homelife',
           'Affecting mobility',
           'Affecting social life/hobbies',
           'Affecting work',
           'Mood',
           'Pain Score',
           'Range of motion in Doc']

# df is a pandas dataframe containing the data frame from figure 1
mu = df[relavant_columns].mean().values
cov = df[relavant_columns].cov().values
number_of_sample = 10


# generate using affine transformation
#c2 = cholesky(cov).T
c2 = sqrtm(cov).T
s = np.matmul(c2, np.random.randn(c2.shape[0], number_of_sample)) + mu.reshape(-1, 1)

# transpose so each row is a sample
s = s.T 

Numpy还有一个内置函数可以直接生成多元法线

s = np.random.multivariate_normal(mu, cov, size=number_of_sample)