【NLP学習ノート】(一)Gensimの基本的な使い方

26594 ワード

インストール:pip install gensim本文の内容は主にhttps://radimrehurek.com/gensim/tut1.html#from-strings-to-vectorsは、中に自分の理解を加えています.理解していないところは、元のドキュメントを直接見ることができます.
1、第一歩、トレーニング用語の準備
簡単にするために、リストdocumentsはコーパスを表し、各文はドキュメントを表し、documentsには9つの要素、すなわち9つのドキュメントから構成されていると仮定します.
from gensim import corpora
documents = ["Human machine interface for lab abc computer applications",
          "A survey of user opinion of computer system response time",
              "The EPS user interface management system",
              "System and human system engineering testing of EPS",
              "Relation of user perceived response time to error measurement",
              "The generation of random binary unordered trees",
              "The intersection graph of paths in trees",
              "Graph minors IV Widths of trees and well quasi ordering",
             "Graph minors A survey"]

2、ステップ2、前処理
分詞(tokenize the documents)、無効語の除去、および語彙に一度しか現れない語.語彙を扱う方法はたくさんありますが、ここでは単純にスペース(whitespace)で単語を分けて、各単語を小文字にして、最後によく使われる単語と一度しか現れない単語を取り除きます.
# remove common words and tokenize
stoplist = set('for a of the and to in'.split())
#  documents,       words    ,        ,     stoplist  word。
texts = [[word for word in document.lower().split() if word not in stoplist]
for document in documents]
# remove words that appear only once,collection python      
from collections import defaultdict
frequency = defaultdict(int)
for text in texts:
    for token in text:
        frequency[token] += 1
texts = [[token for token in text if frequency[token] > 1]
               for text in texts]

from pprint import pprint  # pprint         。
pprint(texts)
#    :
[['human', 'interface', 'computer'],
 ['survey', 'user', 'computer', 'system', 'response', 'time'],
 ['eps', 'user', 'interface', 'system'],
 ['system', 'human', 'system', 'eps'],
 ['user', 'response', 'time'],
 ['trees'],
 ['graph', 'trees'],
 ['graph', 'minors', 'trees'],
 ['graph', 'minors', 'survey']]

3、ステップ3、テキストの量子化
ドキュメントからフィーチャーを抽出する方法には、さまざまな方法があります.ここでは、単語袋モデル(bag-of-words)を簡単に使用して、ドキュメントの特徴を抽出します.このモデルは、各単語がドキュメントに現れる頻度を計算し、これらの頻度をベクトルとして構成し、ドキュメントを量子化します.まず、コーパスに表示されるすべての単語を含む辞書を訓練する必要があります.
#      ,             ,          texts           。
dictionary = corpora.Dictionary(texts)
dictionary.save('/tmp/deerwester.dict')  #              ,            ,      。
print(dictionary) #   :Dictionary(35 unique tokens: ['abc', 'applications', 'computer', 'human', 'interface']...)
# dictionary 35      ,        id
print(dictionary.token2id)#  :{'abc': 0, 'applications': 1, 'computer': 2, 'human': 3, 'interface': 4, 'lab': 5, 'machine': 6, 'opinion': 7, 'response': 8, 'survey': 9, 'system': 10, 'time': 11, 'user': 12, 'eps': 13, 'management': 14, 'engineering': 15, 'testing': 16, 'error': 17, 'measurement': 18, 'perceived': 19, 'relation': 20, 'binary': 21, 'generation': 22, 'random': 23, 'trees': 24, 'unordered': 25, 'graph': 26, 'intersection': 27, 'paths': 28, 'iv': 29, 'minors': 30, 'ordering': 31, 'quasi': 32, 'well': 33, 'widths': 34}



単語辞書は既に構築されており、この辞書では他のテキストをワードバッグモデルで量子化することができる.新しいテキストが「Human computer interaction」であると仮定すると、出力ベクトルは[(2,1),(3,1)],(2,1)の「2」は辞書におけるidが2であることを示し、「1」はHumanがこのドキュメントに1回出現したことを示し、同様である(3,1)Humanを表す辞書のidは3,出現回数は1であり,出力ベクトルのメタグループの順序はidサイズで並べ替えられるべきである.interactionは辞書にはないので無視される.
new_doc = "Human computer interaction"
# dictionary doc2bow        
new_vec = dictionary.doc2bow(new_doc.lower().split())
corpora.MmCorpus.serialize('/tmp/deerwester.mm',new_vec)  #            ,      。
print(new_vec)#  [(2, 1), (3, 1)]

4、最適化
上記のトレーニングでは、コーパスがメモリに完全に存在します.コーパスが大きい場合は、ハードディスク(HDD)に数百万のコーパスが格納されていると仮定して、同じ時間に1つのドキュメントだけがメモリに格納されるように、ドキュメントを一度に取り出すことができます.mycorpus.txtを取得します.
#    
class MyCorpus(object):
    def __iter__(self):
        for line in open('mycorpus.txt'):
            #   line           
            yield dictionary.doc2bow(line.lower().split())
corpus_memory_friendly = MyCorpus()#    corpus      
print(corpus_memory_friendly)#  :<__main__.mycorpus object="" at=""/>

#      
for vector in corpus_memory_friendly:  # load one vector into memory at a time
    print(vector)[(0, 1), (1, 1), (2, 1)]
[(0, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1)]
[(2, 1), (5, 1), (7, 1), (8, 1)]
[(1, 1), (5, 2), (8, 1)]
[(3, 1), (6, 1), (7, 1)]
[(9, 1)]
[(9, 1), (10, 1)]
[(9, 1), (10, 1), (11, 1)]
[(4, 1), (10, 1), (11, 1)]

同様に,辞書dictionaryを構築する過程でもこのようなmemory-friendlyの方式訓練が必要である.
# iteritems          item
from six import iteritems
#           
dictionary = corpora.Dictionary(line.lower().split() for line in open('mycorpus.txt') )
#     ,stop_ids      dictionary  id
stop_ids = [dictionary.token2id[stopword] for stopword in stoplist if stopword in dictionary.token2id]
#        id
once_ids = [tokenid for tokenid, docfreq in iteritem(dictionary.dfs) if docfreq ==1]
#  stop_ids once_ids  dictionary
dictionary.filter_token(stop_ids + once_ids)
#         
dictionary.compactify()
print(dictionary)#  :Dictionary(12 unique tokens)


5、訓練結果を保存するいくつかの方法
  • corpora.MmCorpus.serialize(path, result)
  • corpora.SvmLightCorpus.serialize(path, result)
  • corpora.BleiCorpus.serialize(path, result)
  • corpora.LowCorpus.serialize(path,result)注意すべき時第1種,Market Matrix format,用法例
  • #          corpus
    corpus = [[(1, 0.5)], []]  # make one document empty, for the heck of it
    #  
    corpora.MmCorpus.serialize('/tmp/corpus.mm', corpus)
    #  
    corpus = corpora.MmCorpus('/tmp/corpus.mm')
    print(corpus)#  :MmCorpus(2 documents, 2 features, 1 non-zero entries)
    #             :1.  list2.  corpus,           。
    print(list(corpus))  # calling list() will convert any sequence to a plain Python list
    #  :[[(1, 0.5)], []]
    
    for doc in corpus:
        print(doc)
    #  :[(1, 0.5)][]