我需要一个方法来找到两个一维数组之间的最小卡方对。 例如,一个数组
a = np.array([1, 2, 3])
另一个数组是
b = np.array([0.9, 1, 3.5, 4.5])
我们需要在b
中找到一个长度与a
相同的子数组
sub_b = np.array([0.9, 1, 3.5])
注意sub_b
不应包含重复项。你知道吗
找到两个数组之间最接近的一对。我们选择chi-square = sum((a - sub_b)**2) / len(a)
。所以,我们需要找到具有最小卡方的sub_b
。你知道吗
我使用iteration.permutations
找到sub_b
的所有排列,然后找到最小卡方。你知道吗
from itertools import permutations
def find_chi2_array(b, a):
chi2 = lambda x: sum((x-a)**2) / len(a)
perm = np.array(list(permutations(b, len(a))))
chi2_results = np.apply_along_axis(chi2, 1, perm)
return chi2_results.min(), candidates[chi2_results.argmin()]
但是这种方法非常愚蠢,当b
的长度变大时,内存会很快耗尽。你知道吗
如果在纯python中使用for
循环,则速度太慢。谁能有一个更有效和内存更少的方法?你知道吗
def find_chi2_array_slow(b, a):
chi2 = lambda x: sum((x-a)**2) / len(a)
n = 0
for perm in permutations(b, len(a)):
perm = np.array(perm)
n += 1
if n == 1:
chi2_result = chi2(perm)
elif chi2_result > chi2(perm):
chi2_result = chi2(perm)
return chi2_result
目前没有回答
相关问题 更多 >
编程相关推荐