python - Python 中的相关值
问题描述
所以我有一个代码,它给了我一堆相关的两个参数的随机值。
import numpy as np
import matplotlib.pyplot as plt
def correlated_sample(x, y, sig_x, sig_y, corr, size):
# Given a mean "x" value with uncertainty "sig_x", a mean "y" value
# with uncertainty "sig_y" and there is a correlation, "corr",
# between the two variables, then this function will return
# a random sample of size "size" of 2D values maintaining that correlation.
cov_mat = [[sig_x**2 , sig_x*sig_y*corr],
[sig_y*sig_x*corr, sig_y**2]]
x, y = np.random.multivariate_normal(mean = [x, y], cov_mat, size).T
return (x, y)
# PLOT EXAMPLE
x_arr, y_arr = correlated_sample(0, 5, 0.5, 0.9, 0.5, 10**4)
plt.scatter(x_arr, y_arr, color = 'k', s = 1, alpha = 0.2)
plt.xlim([-4, 4])
plt.ylim([1, 9])
plt.show()
它按预期工作并给出以下输出:
但现在我想做一些更复杂的事情:假设我现在选择一个数据点,例如 20th:x_point = x_arr[20]
和y_point = y_arr[20]
. 现在我想在这个分布中以小的间隔获得该点的随机邻居,但保持相关性。
如果没有相关性,我可以简单地做出:
# Size of the small region around the point.
# In this example it is 50 times smaller than the entire cloud of points.
neighbourhood_extent = 1/50
x_neighbour = np.random.normal(x_point, sig_x*neighbourhood_extent, size = 1)
y_neighbour = np.random.normal(y_point, sig_y*neighbourhood_extent, size = 1)
我会有一个相邻的点。但由于两者之间存在相关性x
,y
我不能这样做。我应该如何进行?
解决方案
推荐阅读
- r - 选择模型时尝试加快嵌套 if else
- css - 为什么我需要重新加载我的 CSS 才能正确显示它?
- javascript - 如果 str1 字符的一部分可以重新排列以匹配 str2,则返回 true 的最快函数,否则返回 false
- python - Robotframework - 侦听器中的致命错误应该结束套件运行
- python - 是否可以通过`source`将参数传递给GDB执行的python脚本?
- python - 基于 3 个连续条件的 Numpy 输出?
- c# - C# 查找列表中价格最接近 0 的行
- android - 过滤从 REST 获取的数据的正确方法是什么?
- actions-on-google - 绕过欢迎消息的显式调用
- xml - XPATH:解析 XML 需要兄弟的孩子等等