2016-10-16 4 views
1

L2でL1の単語が猫(猫の犬、猫の家、猫の木など)に表示される数をPythonで出力する共起行列を作成しようとしています。私のコードは、これまでのところです:Pythonで共起行列を作成する際に奇妙なバグを修正する

co = np.zeros((5,5)) #the matrix 
L1 = ['cat', 'dog', 'house', 'tree', 'car'] #tags 
L2 = ['cat car dog', 'cat house dog', 'cat car', 'cat dog'] #photo text 

n=0 # will hold the sum of each occurance 

for i in range(len(L1)): 
    for j in range(len(L1)): 
     for s in range(len(L2)): 
      #find occurrence but not on same words 
      if L1[i] in L2[s] and L1[j] in L2[s] and L1[i] != L1[j]: 
       n+=1 # sum the number of occurances    
       #output = L1[i], L1[j] # L2[s] 
       #print output 
       co[i][j] = s #add to the matrix 

print co 

出力が代わりに

[[ 0. 3. 1. 0. 2.] 
[ 3. 0. 1. 0. 1.] 
[ 1. 1. 0. 0. 0.] 
[ 0. 0. 0. 0. 0.] 
[ 2. 1. 0. 0. 0.]] 

しかし、次のようになります。

[[ 0. 3. 1. 0. 2.] 
[ 3. 0. 1. 0. 0.] 
[ 1. 1. 0. 0. 0.] 
[ 0. 0. 0. 0. 0.] 
[ 2. 0. 0. 0. 0.]] 

すべての二行目にエラーがあり...ザ・パーツがうまく動作するかどうか、私は出力をチェックしています

output = L1[i], L1[j] # L2[s] 
print output 
    ('cat', 'dog') 
    ('cat', 'dog') 
    ('cat', 'dog') 
    ('cat', 'house') 
    ('cat', 'car') 
    ('cat', 'car') 
    ('dog', 'cat') 
    ('dog', 'cat') 
    ('dog', 'cat') 
    ('dog', 'house') 
    ('dog', 'car') 
    ('house', 'cat') 
    ('house', 'dog') 
    ('car', 'cat') 
    ('car', 'cat') 
    ('car', 'dog') 

だから私は行列を提出する際に起こって何かがあると思う?:

co[i][j] = s 

助言がありますか???

+0

'コ[I、J] = S'を使用してみてください。 – BrenBarn

+0

結果の行列は対称です。 (len(L2)): 'これはあなたに三角形の行列を与えます。これは、範囲(i)の範囲でiのために を使用してパフォーマンスを改善することができます。次に、あなたは主対角線上にミラーコピーを作ることができます – Alexander

+0

おかげで、私はあなたのアドバイスに従いました。co [i、j] = sとco [i] [j]の違いは何ですか? – Artemis

答えて

4

L2の最初の項目のcardog0のインデックスであるため、正しい結果が得られます。ここで

L2でペアの最初の発生に基づいて指標を得るより多くのニシキヘビのアプローチです:

In [158]: L2 = ['cat car dog', 'cat house dog', 'cat car', 'cat dog'] 

In [159]: L2 = [s.split() for s in L2] 

In [160]: combinations = np.column_stack((np.repeat(L1, 5), np.tile(L1, 5))).reshape(5, 5, 2) 
# with 0 as the start of the indices 
In [162]: [[next((i for i, sub in enumerate(L2) if x in sub and y in sub), 0) for x, y in row] for row in combinations] 
Out[162]: 
[[0, 0, 1, 0, 0], 
[0, 0, 1, 0, 0], 
[1, 1, 1, 0, 0], 
[0, 0, 0, 0, 0], 
[0, 0, 0, 0, 0]] 
# with 1 as the start of the indices 
In [163]: [[next((i for i, sub in enumerate(L2, 1) if x in sub and y in sub), 0) for x, y in row] for row in combinations] 
Out[163]: 
[[1, 1, 2, 0, 1], 
[1, 1, 2, 0, 1], 
[2, 2, 2, 0, 0], 
[0, 0, 0, 0, 0], 
[1, 1, 0, 0, 1]] 
+0

あなたは正しいです!ありがとう! – Artemis

関連する問題