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
助言がありますか???
'コ[I、J] = S'を使用してみてください。 – BrenBarn
結果の行列は対称です。 (len(L2)): 'これはあなたに三角形の行列を与えます。これは、範囲(i)の範囲でiのために を使用してパフォーマンスを改善することができます。次に、あなたは主対角線上にミラーコピーを作ることができます – Alexander
おかげで、私はあなたのアドバイスに従いました。co [i、j] = sとco [i] [j]の違いは何ですか? – Artemis