我想通过选择特定 idx 但不使用循环的每一行来计算 2 个矩阵的相关性。
例如:
A = np.array([[ 4, 8, 9, 2, 10, 3, 7, 2, 3, 4],
[ 2, 4, 4, 8, 4, 4, 6, 4, 6, 5],
[10, 7, 3, 2, 4, 2, 5, 2, 7, 10]])
B = np.array([[ 4, 10, 6, 7, 2, 9, 2, 10, 6, 1],
[ 3, 10, 10, 6, 8, 6, 4, 6, 2, 1],
[ 3, 3, 1, 6, 7, 1, 10, 8, 1, 6]])
对于第一行 idx = [1,5,6,8,9],对于第二行和第三行 idx 不同并且 idx 的数字不同(例如 idx = [1, 2, 6])
所以第一个结果是 np.corrcoef(A[0, idx], B[0, idx]).
如何只使用 numpy 对所有行执行此操作?
我的代码如下
threshold = np.arange(80, 161, 5)
sample_math = np.random.normal(60, 10, size=(len(threshold), 10**4))
sample_rus = np.random.normal(60, 10, size=(len(threshold), 10**4))
sample = sample_rus + sample_math
idx_row, idx_col = np.where(sample > threshold[:, None])
np.corrcoef(sample_math[idx_row, idx_col], sample_rus[idx_row, idx_col])
这里的问题是变量 sample_math[idx_row, idx_col] 和 sample_rus[idx_row, idx_col] 的形状是 (some number,) 所以 python 只需一次计算所有行的 corr
您可以使用循环分别计算每一行的相关性,例如:
...
idx = [[1,5,6,8,9], [1, 2, 6], [0, 3, 7]]
correlations = []
for i in range(A.shape[0]):
corr = np.corrcoef(A[i, idx[i]], B[i, idx[i]])[0, 1]
correlations.append(corr)
correlations = np.array(correlations)
希望对您有所帮助。
干杯:)