2017-02-09 2 views
0

私は行間にいくつの類似の列があるかを見つけるのに役立つ基本的なスクリプトを書こうとしています。情報は非常に簡単で、何かのように:などPythonで2つの行の間にある同じ列要素の数を比較する

array = np.array([0 1 0 0 1 0 0], [0 0 1 0 1 1 0]) 

私は、リストのすべての順列との間に、このスクリプトを実行する必要があるので、2行に比べて、1行目は3行に比べて1行う、

ご協力いただければ幸いです。

+0

ご例えば所望の出力だ?とnumpyの配列ですか。 3列目は何を話しているのですか?私は2行しか見ることができません。コードが無効です。 –

+1

"類似"をどのように定義しますか? – Divakar

答えて

0

あなたの見出しの質問は、基本的なnumpyテクニックで対処できます。

first = a[:, None, :] # None creates a new dimension to make space for a second row axis 
second = a[None, :, :] # Same but new dim in first axis 
# observe that axes 0 and 1 in these two array are arranged as for a distance map 
# a binary operation between arrays so layed out will trigger broadcasting, i.e. numpy will compute all possible pairs in the appropriate positions 
full_overlap_map = first == second # has shape nrow x nrow x ncol 
similarity_table = full_overlap_map.sum(axis=-1) # shape nrow x nrow 
0

row_m = a[m, :] # this selects row index m and all column indices, thus: row m 
row_n = a[n, :] 
shared = row_m == row_n # this compares row_m and row_n element-by-element storing each individual result (True or False) in a separate cell, the result thus has the same shape as row_m and row_n 
overlap = shared.sum() # this sums over all elements in shared, since False is encoded as 0 and True as 1 this returns the number of shared elements. 

行のすべてのペアにこのレシピを適用する最も簡単な方法は、放送である:あなたは2-Dのnumpyの配列aを持っていて、行mnを比較したいと仮定しましょうあなたはすべての行に頼ることができるバイナリ「と同様の列を」高く評価されている場合の可能性がある場合、カウントは単に

def count_sim_cols(row0, row1): 
    return np.sum(row0*row1) 

ですあなたは、これがそれからちょうど

def count_sim_cols(row0, row1): 
    return np.sum(np.abs(row0 - row1) < tol) 

で、tolを言って、いくつかの小さな値を「類似性」の許容範囲を希望の場合は、値の範囲が広く、あなただけの比較

def count_sim_cols(row0, row1): 
    return np.sum(row0 == row1) 

で製品を置き換えますカウントを取得するために二重ネストループすることができます。 Xと仮定するとn

sim_counts = {} 
for i in xrange(n): 
    for j in xrange(i + 1, n): 
     sim_counts[(i, j)] = count_sim_cols(X[i], X[j]) 
関連する問題