python生成有限范围内混合高斯分布的点
时间: 2023-09-15 21:19:10 浏览: 94
生成有限范围内的混合高斯分布点可以使用Python的NumPy和SciPy库。以下是一个示例代码,它生成了一个位于[-10, 10] x [-10, 10]范围内的混合高斯分布点。
```python
import numpy as np
from scipy.stats import multivariate_normal
# 设定混合高斯分布的参数
means = np.array([[-5, 5], [5, -5], [0, 0]])
covs = np.array([[[2, 1], [1, 2]], [[2, -1], [-1, 2]], [[3, 0], [0, 1]]])
weights = np.array([0.3, 0.3, 0.4])
# 生成混合高斯分布点
num_samples = 1000
samples = []
for i in range(num_samples):
# 随机选择一个高斯分布
k = np.random.choice(len(weights), p=weights)
# 从该高斯分布中采样一个点
sample = np.random.multivariate_normal(means[k], covs[k])
# 如果点不在[-10, 10] x [-10, 10]范围内,则重新采样
while (sample < -10).any() or (sample > 10).any():
sample = np.random.multivariate_normal(means[k], covs[k])
samples.append(sample)
# 可视化生成的点
import matplotlib.pyplot as plt
samples = np.array(samples)
plt.scatter(samples[:, 0], samples[:, 1])
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()
```
在上面的代码中,我们首先定义了三个高斯分布的均值、协方差矩阵和权重,然后使用`np.random.choice`函数随机选择一个高斯分布,并使用`np.random.multivariate_normal`函数从该高斯分布中采样一个点。如果采样得到的点不在[-10, 10] x [-10, 10]范围内,则使用`while`循环重新采样。最后,我们使用Matplotlib库将生成的点可视化。
阅读全文
相关推荐

















