在针对供需匹配模型做数值实验时时,遇到一个问题:当面临需求不确定性,如果不同需求点之间存在相关性,如何验证模型的有效性。
因此,在数值实验中需要生成具有一定相关性的需求随机数。
# 导入数组和画图包
import numpy as np
import matplotlib.pyplot as plt
# 设定样本数量
num_samples = 500
# The desired mean values of the sample.均值
mu = np.array([6, 8, 10])
# The desired covariance matrix.协方差矩阵
r = np.array([
[ 2.60, -1.55, -3.00],
[ -1.55, 3.20, 1.40],
[ -3.00, 1.40, 2.25]
])
# Generate the random samples.调用相关函数,生成随机数
rng = np.random.default_rng()
y = rng.multivariate_normal(mu, r, size=num_samples)
# Plot various projections of the samples.
# 从三组数据中任意取两组数据进行绘制,观察相关性
plt.subplot(2,2,1)
plt.plot(y[:,0], y[:,1], 'b.', alpha=0.25)
plt.plot(mu[0], mu[1], 'ro', ms=3.5)
plt.ylabel('y[1]')
plt.axis('equal')
plt.grid(True)
plt.subplot(2,2,3)
plt.plot(y[:,0], y[:,2], 'b.', alpha=0.25)
plt.plot(mu[0], mu[2], 'ro', ms=3.5)
plt.xlabel('y[0]')
plt.ylabel('y[2]')
plt.axis('equal')
plt.grid(True)
plt.subplot(2,2,4)
plt.plot(y[:,1], y[:,2], 'b.', alpha=0.25)
plt.plot(mu[1], mu[2], 'ro', ms=3.5)
plt.xlabel('y[1]')
plt.axis('equal')
plt.grid(True)
plt.show()
结果如下图所示:
参考:
https://stackoverflow.com/questions/16024677/generate-correlated-data-in-python-3-3