行列内の列のペアワイズ相関をとる関数(組み込みのようpdist
にscipy.stats
)を作成しましたが、引数で指定された欠落値を処理できますna_values
。すなわち:
def my_pdist(X, dist_func, na_values=["NA"]):
X = array(X, dtype=object)
num_rows, num_cols = X.shape
dist_matrix = []
for col1 in range(num_cols):
pdist_row = []
for col2 in range(num_cols):
pairs = array([[x, y] for x, y in zip(X[:, col1], X[:, col2]) \
if (x not in na_values) and (y not in na_values)])
if len(pairs) == 0:
continue
dist = dist_func(pairs[:, 0],
pairs[:, 1])
pdist_row.append(dist)
dist_matrix.append(pdist_row)
dist_matrix = array(dist_matrix)
return dist_matrix
ここdist_func
で、は距離メトリックを指定する関数です。この機能を高速化する方法はありますか?使用例は次のとおりです。
def spearman_dist(u, v, na_vals=["NA"]):
matrix = [[x, y] for x, y in zip(u, v) \
if (u not in na_vals) and (v not in na_vals)]
matrix = array(matrix)
spearman = scipy.stats.spearmanr(matrix[:, 0], matrix[:, 1])[0]
return 1 - spearman
my_pdist(X, spearman_dist, na_values=["NA"])
どうすればこれをベクトル化/高速化できますか?