パフォーマンスを向上させるには、リスト内包表記をベクトル化コードで置き換える必要があります。以下のスニペットに示すように、これは簡単にnumpyののpdist
とsquareform
を介して実装することができます。
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from scipy.spatial.distance import pdist, squareform
titles = [
'A New Hope',
'The Empire Strikes Back',
'Return of the Jedi',
'The Phantom Menace',
'Attack of the Clones',
'Revenge of the Sith',
'The Force Awakens',
'A Star Wars Story',
'The Last Jedi',
]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(titles)
cs_title = squareform(pdist(X.toarray(), 'cosine'))
デモ:X.toarray().shape
利回り(9L, 21L)
が原因で上記の玩具の例では9つのタイトルがあること
In [87]: X
Out[87]:
<9x21 sparse matrix of type '<type 'numpy.int64'>'
with 30 stored elements in Compressed Sparse Row format>
In [88]: X.toarray()
Out[88]:
array([[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]], dtype=int64)
In [89]: vectorizer.get_feature_names()
Out[89]:
[u'attack',
u'awakens',
u'back',
u'clones',
u'empire',
u'force',
u'hope',
u'jedi',
u'last',
u'menace',
u'new',
u'of',
u'phantom',
u'return',
u'revenge',
u'sith',
u'star',
u'story',
u'strikes',
u'the',
u'wars']
In [90]: np.set_printoptions(precision=2)
In [91]: print(cs_title)
[[ 0. 1. 1. 1. 1. 1. 1. 1. 1. ]
[ 1. 0. 0.75 0.71 0.75 0.75 0.71 1. 0.71]
[ 1. 0.75 0. 0.71 0.5 0.5 0.71 1. 0.42]
[ 1. 0.71 0.71 0. 0.71 0.71 0.67 1. 0.67]
[ 1. 0.75 0.5 0.71 0. 0.5 0.71 1. 0.71]
[ 1. 0.75 0.5 0.71 0.5 0. 0.71 1. 0.71]
[ 1. 0.71 0.71 0.67 0.71 0.71 0. 1. 0.67]
[ 1. 1. 1. 1. 1. 1. 1. 0. 1. ]
[ 1. 0.71 0.42 0.67 0.71 0.71 0.67 1. 0. ]]
お知らせおよび21の異なる語であり、cs_title
は9 by 9の配列である。
私はこれを考慮しましたが、同等の出力を製品に実装する方法がわかりませんでしたか? – user7347576
あなたの質問に含まれているコードは、例えば 'cs_pt = [pre_pt in a pre_pt for a pre_pt]には、ベクトルを生成します。しかしコサインの類似点の集合ごとに行列を求めたくないですか? –
ええ、それは望ましい出力でした... – user7347576