LoginSignup
1
2

More than 5 years have passed since last update.

gensimで文章をベクトルに変換する

Last updated at Posted at 2016-06-25

From Strings to Vectorsの章をやってみました。

stoplistの部分で必要のない単語を除外しています。

ストップワードとは
あまりにたくさん検索にかかりすぎるので、検索精度の向上のためには検索対象から除外せざるを得ない語。助詞や助動詞などの機能語(日本語ならば「は」「の」「です」「ます」など、英語ならば「the」「of」「is」など)は、殆んどの場合これに該当する。
※はてな参照

sample.py

import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

from gensim import corpora, models, similarities

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"]


# remove common words and tokenize
stoplist = set('for a of the and to in'.split())
texts = [[word for word in document.lower().split() if word not in stoplist]
  for document in documents]

# remove words that appear only once
from collections import defaultdict
frequency = defaultdict(int)

# print(texts)

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   # pretty-printer
# pprint(texts)

dictionary = corpora.Dictionary(texts)
# print(dictionary)

#id付きで出力
# print(dictionary.token2id)

#文章ベクトルへ変換
corpus = [dictionary.doc2bow(text) for text in texts]
print(corpus)


公式チュートリアル
https://radimrehurek.com/gensim/tut1.html

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2