Python for NLP: Gensim ライブラリを使った作業 (パート1)

Python for NLPの連載は今回で10回目です。

前回は、StanfordCoreNLPライブラリを使用して、さまざまなNLPタスクを実行する方法について説明しました。

今回は、Pythonのもう一つの非常に便利なNLPライブラリであるGensimライブラリを探ります。

Gensimは主にトピックモデリング用に開発されました。

しかし現在では、単語をベクトルに変換する(word2vec)、文書をベクトルに変換する(doc2vec)、テキストの類似性を見つける、テキストの要約など、他の様々なNLPタスクもサポートしています。

今回と次回の連載では、これらのタスクを実行するためにGensimライブラリがどのように利用されているかを見ていきます。

Gensim のインストール

Python のライブラリのインストールに pip installer を使用している場合、以下のコマンドで Gensim ライブラリをダウンロードすることができます。

$ pip install gensim


また、PythonのAnacondaディストリビューションを使用している場合、以下のコマンドを実行してGensimライブラリをインストールすることができます。

$ conda install -c anaconda gensim


それでは、Gensim ライブラリを用いて、どのように様々な NLP タスクを実行できるかを見ていきましょう。

辞書の作成

統計アルゴリズムは数字を扱うが、自然言語には文字という形でデータが含まれている。

そのため、単語を数値に変換する仕組みが必要である。

同様に、数値に様々な処理を施した後、数値をテキストに戻す必要がある。

このような機能を実現する一つの方法として、文書中の一意な単語ごとに数値IDを付与した辞書を作成することが考えられる。

この辞書を使って、ある単語の数値に相当する部分を探したり、その逆も可能です。

インメモリオブジェクトを使用した辞書の作成

Python の Gensim ライブラリを使うと、単語と ID を対応付ける辞書を簡単に作成することができます。

以下のスクリプトを見てください。

import gensim
from gensim import corpora
from pprint import pprint


text = ["""In computer science, artificial intelligence (AI),
             sometimes called machine intelligence, is intelligence
             demonstrated by machines, in contrast to the natural intelligence
             displayed by humans and animals. Computer science defines
             AI research as the study of intelligent agents: any device that
             perceives its environment and takes actions that maximize its chance
             of successfully achieving its goals."""]


tokens = [[token for token in sentence.split()] for sentence in text]
gensim_dictionary = corpora.Dictionary(tokens)


print("The dictionary has: " +str(len(gensim_dictionary)) + " tokens")


for k, v in gensim_dictionary.token2id.items():
    print(f'{k:{15}} {v:{10}}')


上のスクリプトでは、まず gensim ライブラリをインポートし、さらに corpora モジュールをインポートしています。

次に、いくつかのテキスト(Wikipedia の人工知能の記事の最初の段落の部分)を text 変数に格納しています。

辞書を作成するには、テキストから単語のリスト (トークン) を取得する必要があります。

次の行では、文書を文に分割し、文を単語に分割しています。

tokens = [[token for token in sentence.split()] for sentence in text]


これで、辞書を作成する準備ができました。

これを行うには、corpora モジュールの Dictionary オブジェクトを使用して、トークンのリストを渡します。

最後に、新しく作成した辞書の内容を表示するために、Dictionary クラスの token2id オブジェクトを使用します。

上のスクリプトの出力はこのようになります。

The dictionary has: 46 tokens
(AI),                    0
AI                       1
Computer                 2
In                       3
achieving                4
actions                  5
agents:                  6
and                      7
animals.                 8
any                      9
artificial              10
as                      11
by                      12
called                  13
chance                  14
computer                15
contrast                16
defines                 17
demonstrated            18
device                  19
displayed               20
environment             21
goals.                  22
humans                  23
in                      24
intelligence            25
intelligence,           26
intelligent             27
is                      28
its                     29
machine                 30
machines,               31
maximize                32
natural                 33
of                      34
perceives               35
research                36
science                 37
science,                38
sometimes               39
study                   40
successfully            41
takes                   42
that                    43
the                     44
to                      45


この出力は、テキストに含まれる一意な単語と、その単語に割り当てられた数値のIDを示している。

単語やトークンが辞書のキーで、IDが値である。

以下のスクリプトを使えば、個々の単語に割り当てられたIDを確認することもできる。

print(gensim_dictionary.token2id["study"])


上のスクリプトでは、辞書のキーとして「study」という単語を渡している。

出力には、対応する値、つまり「study」という単語のID、40が表示されるはずである。

同様に、以下のスクリプトを使えば、特定のIDに対応するキーや単語を検索することができる。

print(list(gensim_dictionary.token2id.keys())[list(gensim_dictionary.token2id.values()).index(40)])


トークンとそれに対応するIDを表示するために、for-loopを使用した。

しかし、このように辞書を印刷することで、トークンとそのIDを直接印刷することができる。

print(gensim_dictionary.token2id)


出力は以下のようになります。

{'(AI),': 0, 'AI': 1, 'Computer': 2, 'In': 3, 'achieving': 4, 'actions': 5, 'agents:': 6, 'and': 7, 'animals.': 8, 'any': 9, 'artificial': 10, 'as': 11, 'by': 12, 'called': 13, 'chance': 14, 'computer': 15, 'contrast': 16, 'defines': 17, 'demonstrated': 18, 'device': 19, 'displayed': 20, 'environment': 21, 'goals.': 22, 'humans': 23, 'in': 24, 'intelligence': 25, 'intelligence,': 26, 'intelligent': 27, 'is': 28, 'its': 29, 'machine': 30, 'machines,': 31, 'maximize': 32, 'natural': 33, 'of': 34, 'perceives': 35, 'research': 36, 'science': 37, 'science,': 38, 'sometimes': 39, 'study': 40, 'successfully': 41, 'takes': 42, 'that': 43, 'the': 44, 'to': 45}


この出力は、ループを使って出力されたものほど明確ではないかもしれませんが、それでも目的は達成されています。

では、新しい文書を使って、既存の辞書にさらにトークンを追加する方法を見てみましょう。

次のスクリプトを見てください。

text = ["""Colloquially, the term "artificial intelligence" is used to
           describe machines that mimic "cognitive" functions that humans
           associate with other human minds, such as "learning" and "problem solving"""]


tokens = [[token for token in sentence.split()] for sentence in text]
gensim_dictionary.add_documents(tokens)


print("The dictionary has: " + str(len(gensim_dictionary)) + " tokens")
print(gensim_dictionary.token2id)


上のスクリプトでは、Wikipediaの人工知能の記事の最初の段落の後半を含む新しい文書がある。

テキストをトークンに分割し、add_documents メソッドを呼び出して既存の辞書にトークンを追加しています。

最後に、更新された辞書をコンソールに表示します。

このコードの出力は次のようになります。

The dictionary has: 65 tokens
{'(AI),': 0, 'AI': 1, 'Computer': 2, 'In': 3, 'achieving': 4, 'actions': 5, 'agents:': 6, 'and': 7, 'animals.': 8, 'any': 9, 'artificial': 10, 'as': 11, 'by': 12, 'called': 13, 'chance': 14, 'computer': 15, 'contrast': 16, 'defines': 17, 'demonstrated': 18, 'device': 19, 'displayed': 20, 'environment': 21, 'goals.': 22, 'humans': 23, 'in': 24, 'intelligence': 25, 'intelligence,': 26, 'intelligent': 27, 'is': 28, 'its': 29, 'machine': 30, 'machines,': 31, 'maximize': 32, 'natural': 33, 'of': 34, 'perceives': 35, 'research': 36, 'science': 37, 'science,': 38, 'sometimes': 39, 'study': 40, 'successfully': 41, 'takes': 42, 'that': 43, 'the': 44, 'to': 45, '"artificial': 46, '"cognitive"': 47, '"learning"': 48, '"problem': 49, 'Colloquially,': 50, 'associate': 51, 'describe': 52, 'functions': 53, 'human': 54, 'intelligence"': 55, 'machines': 56, 'mimic': 57, 'minds,': 58, 'other': 59, 'solving': 60, 'such': 61, 'term': 62, 'used': 63, 'with': 64}


以前は 45 個のトークンが辞書に登録されていましたが、現在は 65 個のトークンが登録されていることがわかります。

テキストファイルによる辞書の作成

前節では、インメモリーテキストを利用した。

ハードディスクからテキストファイルを読み込んで辞書を作成したい場合はどうすればよいでしょうか。

そのためには、gensim.utilsライブラリの simple_process メソッドを使用します。

このメソッドを使う利点は、テキストファイルを一行ずつ読んで、その行に含まれるトークンを返してくれることです。

辞書を作成するために、テキストファイル全体をメモリに読み込む必要はないのです。

次の例を実行する前に、ファイル「file1.txt」を作成し、次のテキストをファイルに追加する(これはWikipediaの地球温暖化に関する記事の最初の段落の前半部分である)。

Global warming is a long-term rise in the average temperature of the Earth's climate system, an aspect of climate change shown by temperature measurements and by multiple effects of the warming. Though earlier geological periods also experienced episodes of warming, the term commonly refers to the observed and continuing increase in average air and ocean temperatures since 1900 caused mainly by emissions of greenhouse gasses in the modern industrial economy.


次に、テキストファイル “file1.txt “のトークンを含む辞書を作成しよう。

from gensim.utils import simple_preprocess
from smart_open import smart_open
import os


gensim_dictionary = corpora.Dictionary(simple_preprocess(sentence, deacc=True) for sentence in open(r'E:text filesfile1.txt', encoding='utf-8'))


print(gensim_dictionary.token2id)


上のスクリプトでは、simple_preprocess メソッドを使ってテキストファイル “file1.txt” を一行ずつ読み込んでいます。

このメソッドはドキュメントの各行に含まれるトークンを返します。

そして、そのトークンを使って辞書を作成します。

出力には、以下のようにトークンとそれに対応するIDが表示されるはずです。

{'average': 0, 'climate': 1, 'earth': 2, 'global': 3, 'in': 4, 'is': 5, 'long': 6, 'of': 7, 'rise': 8, 'system': 9, 'temperature': 10, 'term': 11, 'the': 12, 'warming': 13, 'an': 14, 'and': 15, 'aspect': 16, 'by': 17, 'change': 18, 'effects': 19, 'measurements': 20, 'multiple': 21, 'shown': 22, 'also': 23, 'earlier': 24, 'episodes': 25, 'experienced': 26, 'geological': 27, 'periods': 28, 'though': 29, 'air': 30, 'commonly': 31, 'continuing': 32, 'increase': 33, 'observed': 34, 'ocean': 35, 'refers': 36, 'temperatures': 37, 'to': 38, 'caused': 39, 'economy': 40, 'emissions': 41, 'gasses': 42, 'greenhouse': 43, 'industrial': 44, 'mainly': 45, 'modern': 46, 'since': 47}


同様に、複数のテキストファイルを読み込んで辞書を作成することもできる。

別のファイル「file2.txt」を作成し、そのファイルに次のテキストを追加する(Wikipediaの地球温暖化に関する記事の第1段落の後半部分である)。

In the modern context the terms global warming and climate change are commonly used interchangeably, but climate change includes both global warming and its effects, such as changes to precipitation and impacts that differ by region.[7][8] Many of the observed warming changes since the 1950s are unprecedented in the instrumental temperature record, and in historical and paleoclimate proxy records of climate change over thousands to millions of years.


file2.txt “を “file1.txt “と同じディレクトリに保存する。

次のスクリプトは、両方のファイルを読み込んで、2つのファイルのテキストをもとに辞書を作成する。

from gensim.utils import simple_preprocess
from smart_open import smart_open
import os


class ReturnTokens(object):
    def __init__(self, dir_path):
        self.dir_path = dir_path


def __iter__(self):
        for file_name in os.listdir(self.dir_path):
            for sentence in open(os.path.join(self.dir_path, file_name), encoding='utf-8'):
                yield simple_preprocess(sentence)


path_to_text_directory = r"E:   ext files"
gensim_dictionary = corpora.Dictionary(ReturnTokens(path_to_text_directory))


print(gensim_dictionary.token2id)


上のスクリプトでは、メソッド ReturnTokens に “file1.txt” と “file2.txt” を含むディレクトリのパスを唯一のパラメーターとして渡している。

このメソッドの内部では、ディレクトリ内のすべてのファイルを繰り返し処理し、各ファイルを一行ずつ読み込んでいる。

simple_preprocess` メソッドは、各行のトークンを作成します。

各行のトークンは、”yield” キーワードを使って呼び出し元の関数に返されます。

出力には、以下のトークンとそのIDが表示されるはずです。

{'average': 0, 'climate': 1, 'earth': 2, 'global': 3, 'in': 4, 'is': 5, 'long': 6, 'of': 7, 'rise': 8, 'system': 9, 'temperature': 10, 'term': 11, 'the': 12, 'warming': 13, 'an': 14, 'and': 15, 'aspect': 16, 'by': 17, 'change': 18, 'effects': 19, 'measurements': 20, 'multiple': 21, 'shown': 22, 'also': 23, 'earlier': 24, 'episodes': 25, 'experienced': 26, 'geological': 27, 'periods': 28, 'though': 29, 'air': 30, 'commonly': 31, 'continuing': 32, 'increase': 33, 'observed': 34, 'ocean': 35, 'refers': 36, 'temperatures': 37, 'to': 38, 'caused': 39, 'economy': 40, 'emissions': 41, 'gasses': 42, 'greenhouse': 43, 'industrial': 44, 'mainly': 45, 'modern': 46, 'since': 47, 'are': 48, 'context': 49, 'interchangeably': 50, 'terms': 51, 'used': 52, 'as': 53, 'both': 54, 'but': 55, 'changes': 56, 'includes': 57, 'its': 58, 'precipitation': 59, 'such': 60, 'differ': 61, 'impacts': 62, 'instrumental': 63, 'many': 64, 'record': 65, 'region': 66, 'that': 67, 'unprecedented': 68, 'historical': 69, 'millions': 70, 'over': 71, 'paleoclimate': 72, 'proxy': 73, 'records': 74, 'thousands': 75, 'years': 76}


バグオブワーズコーパスの作成

辞書には、単語とそれに対応する数値の対応表が格納されています。

GensimライブラリのBag of Wordsコーパスは辞書をベースにしており、各単語のIDとその単語の出現頻度が格納されています。

インメモリオブジェクトからのBag of Wordsコーパスの作成

次のスクリプトを見てください。

import gensim
from gensim import corpora
from pprint import pprint


text = ["""In computer science, artificial intelligence (AI),
           sometimes called machine intelligence, is intelligence
           demonstrated by machines, in contrast to the natural intelligence
           displayed by humans and animals. Computer science defines
           AI research as the study of intelligent agents: any device that
           perceives its environment and takes actions that maximize its chance
           of successfully achieving its goals."""]


tokens = [[token for token in sentence.split()] for sentence in text]


gensim_dictionary = corpora.Dictionary()
gensim_corpus = [gensim_dictionary.doc2bow(token, allow_update=True) for token in tokens]


print(gensim_corpus)


上のスクリプトでは、テキストをトークンに分割している。

次に、corpora モジュールの Dictionary オブジェクトを初期化する。

このオブジェクトには doc2bow というメソッドが含まれており、基本的に 2 つのタスクを実行します。

  • もし、その単語がすでにコーパスに存在する場合は、その単語の頻度カウントを増加させる。
  • そうでなければ、その単語をコーパスに挿入し、その頻度カウントを1に設定する。

上記のスクリプトの出力は以下のようになる。

[[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 2), (8, 1), (9, 1), (10, 1), (11, 1), (12, 2), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), (20, 1), (21, 1), (22, 1), (23, 1), (24, 1), (25, 3), (26, 1), (27, 1), (28, 1), (29, 3), (30, 1), (31, 1), (32, 1), (33, 1), (34, 2), (35, 1), (36, 1), (37, 1), (38, 1), (39, 1), (40, 1), (41, 1), (42, 1), (43, 2), (44, 2), (45, 1)]]


この出力はあなたにとって意味をなさないかもしれない。

説明しよう。

最初のタプル(0,1)は基本的にID 0の単語がテキスト中に1回出現したことを意味する。

同様に、(25, 3)は、IDが25の単語が文書中に3回出現したことを意味します。

では、わかりやすくするために、単語と出現回数を表示してみましょう。

先ほどのスクリプトの最後に、以下のコードを追加してください。

word_frequencies = [[(gensim_dictionary[id], frequence) for id, frequence in couple] for couple in gensim_corpus]
print(word_frequencies)


出力はこのようになる。

[[('(AI),', 1), ('AI', 1), ('Computer', 1), ('In', 1), ('achieving', 1), ('actions', 1), ('agents:', 1), ('and', 2), ('animals.', 1), ('any', 1), ('artificial', 1), ('as', 1), ('by', 2), ('called', 1), ('chance', 1), ('computer', 1), ('contrast', 1), ('defines', 1), ('demonstrated', 1), ('device', 1), ('displayed', 1), ('environment', 1), ('goals.', 1), ('humans', 1), ('in', 1), ('intelligence', 3), ('intelligence,', 1), ('intelligent', 1), ('is', 1), ('its', 3), ('machine', 1), ('machines,', 1), ('maximize', 1), ('natural', 1), ('of', 2), ('perceives', 1), ('research', 1), ('science', 1), ('science,', 1), ('sometimes', 1), ('study', 1), ('successfully', 1), ('takes', 1), ('that', 2), ('the', 2), ('to', 1)]]


出力から、”intelligence “という単語が3回出現していることがわかる。

同様に、”that “という単語は2回現れる。

テキストファイルからBag of Wordsコーパスを作成する。

辞書と同じように、テキストファイルを読み込んでBag of Wordsコーパスを作ることもできる。

次のコードを見てください。

from gensim.utils import simple_preprocess
from smart_open import smart_open
import os


tokens = [simple_preprocess(sentence, deacc=True) for sentence in open(r'E: ext filesile1.txt', encoding='utf-8')]


gensim_dictionary = corpora.Dictionary()
gensim_corpus = [gensim_dictionary.doc2bow(token, allow_update=True) for token in tokens]
word_frequencies = [[(gensim_dictionary[id], frequence) for id, frequence in couple] for couple in gensim_corpus]


print(word_frequencies)


上のスクリプトでは、”file1.txt “を使ってBag of Wordsコーパスを作成した。

出力には、Wikipediaの地球温暖化の記事の最初のパラグラフにある単語が表示されているはずである。

[[('average', 1), ('climate', 1), ('earth', 1), ('global', 1), ('in', 1), ('is', 1), ('long', 1), ('of', 1), ('rise', 1), ('system', 1), ('temperature', 1), ('term', 1), ('the', 2), ('warming', 1)], [('climate', 1), ('of', 2), ('temperature', 1), ('the', 1), ('warming', 1), ('an', 1), ('and', 1), ('aspect', 1), ('by', 2), ('change', 1), ('effects', 1), ('measurements', 1), ('multiple', 1), ('shown', 1)], [('of', 1), ('warming', 1), ('also', 1), ('earlier', 1), ('episodes', 1), ('experienced', 1), ('geological', 1), ('periods', 1), ('though', 1)], [('average', 1), ('in', 1), ('term', 1), ('the', 2), ('and', 2), ('air', 1), ('commonly', 1), ('continuing', 1), ('increase', 1), ('observed', 1), ('ocean', 1), ('refers', 1), ('temperatures', 1), ('to', 1)], [('in', 1), ('of', 1), ('the', 1), ('by', 1), ('caused', 1), ('economy', 1), ('emissions', 1), ('gasses', 1), ('greenhouse', 1), ('industrial', 1), ('mainly', 1), ('modern', 1), ('since', 1)]]


この出力では、”of”, “the”, “by”, “and “といった単語が2回出現していることがわかる。

同様に、複数のテキストファイルを使って、以下のようなBag of Wordコーパスを作成することができる。

from gensim.utils import simple_preprocess
from smart_open import smart_open
import os


class ReturnTokens(object):
    def __init__(self, dir_path):
        self.dir_path = dir_path


def __iter__(self):
        for file_name in os.listdir(self.dir_path):
            for sentence in open(os.path.join(self.dir_path, file_name), encoding='utf-8'):
                yield simple_preprocess(sentence)


path_to_text_directory = r"E:   ext files"


gensim_dictionary = corpora.Dictionary()
gensim_corpus = [gensim_dictionary.doc2bow(token, allow_update=True) for token in ReturnTokens(path_to_text_directory)]
word_frequencies = [[(gensim_dictionary[id], frequence) for id, frequence in couple] for couple in gensim_corpus]


print(word_frequencies)


上のスクリプトの出力は以下のようになる。

[[('average', 1), ('climate', 1), ('earth', 1), ('global', 1), ('in', 1), ('is', 1), ('long', 1), ('of', 1), ('rise', 1), ('system', 1), ('temperature', 1), ('term', 1), ('the', 2), ('warming', 1)], [('climate', 1), ('of', 2), ('temperature', 1), ('the', 1), ('warming', 1), ('an', 1), ('and', 1), ('aspect', 1), ('by', 2), ('change', 1), ('effects', 1), ('measurements', 1), ('multiple', 1), ('shown', 1)], [('of', 1), ('warming', 1), ('also', 1), ('earlier', 1), ('episodes', 1), ('experienced', 1), ('geological', 1), ('periods', 1), ('though', 1)], [('average', 1), ('in', 1), ('term', 1), ('the', 2), ('and', 2), ('air', 1), ('commonly', 1), ('continuing', 1), ('increase', 1), ('observed', 1), ('ocean', 1), ('refers', 1), ('temperatures', 1), ('to', 1)], [('in', 1), ('of', 1), ('the', 1), ('by', 1), ('caused', 1), ('economy', 1), ('emissions', 1), ('gasses', 1), ('greenhouse', 1), ('industrial', 1), ('mainly', 1), ('modern', 1), ('since', 1)], [('climate', 1), ('global', 1), ('in', 1), ('the', 2), ('warming', 1), ('and', 1), ('change', 1), ('commonly', 1), ('modern', 1), ('are', 1), ('context', 1), ('interchangeably', 1), ('terms', 1), ('used', 1)], [('climate', 1), ('global', 1), ('warming', 1), ('and', 2), ('change', 1), ('effects', 1), ('to', 1), ('as', 1), ('both', 1), ('but', 1), ('changes', 1), ('includes', 1), ('its', 1), ('precipitation', 1), ('such', 1)], [('in', 1), ('of', 1), ('temperature', 1), ('the', 3), ('warming', 1), ('by', 1), ('observed', 1), ('since', 1), ('are', 1), ('changes', 1), ('differ', 1), ('impacts', 1), ('instrumental', 1), ('many', 1), ('record', 1), ('region', 1), ('that', 1), ('unprecedented', 1)], [('climate', 1), ('in', 1), ('of', 2), ('and', 2), ('change', 1), ('to', 1), ('historical', 1), ('millions', 1), ('over', 1), ('paleoclimate', 1), ('proxy', 1), ('records', 1), ('thousands', 1), ('years', 1)]]


TF-IDFコーパスの作成

Bag of wordsのアプローチは、テキストを数値に変換するのに適している。

しかし、1つの欠点がある。

それは、特定の文書での出現率に基づいて、単語にスコアを割り当てることである。

このため、その単語が他の文書でも高い頻度で出現している可能性があるという事実が考慮されていない。

TF-IDFはこの問題を解決する。

用語の出現頻度は次のように計算される。

Term frequency = (Frequency of the word in a document)/(Total words in the document)


そして、逆文書頻度は次のように計算される。

IDF(word) = Log((Total number of documents)/(Number of documents containing the word))


Gensimライブラリを使えば、TF-IDFコーパスを簡単に作成することができる。

import gensim
from gensim import corpora
from pprint import pprint


text = ["I like to play Football",
       "Football is the best game",
       "Which game do you like to play ?"]


tokens = [[token for token in sentence.split()] for sentence in text]


gensim_dictionary = corpora.Dictionary()
gensim_corpus = [gensim_dictionary.doc2bow(token, allow_update=True) for token in tokens]


from gensim import models
import numpy as np


tfidf = models.TfidfModel(gensim_corpus, smartirs='ntc')


for sent in tfidf[gensim_corpus]:
    print([[gensim_dictionary[id], np.around(frequency, decimals=2)] for id, frequency in sent])


TF-IDF の値を求めるには、Gensim ライブラリの models モジュールにある TfidfModel クラスを利用することができる。

TfidfModel` クラスのコンストラクタに、単語コーパスのバッグをパラメータとして渡すだけでよい。

出力では、3つの文に含まれる全ての単語と、そのTF-IDF値が表示されます。

[['Football', 0.3], ['I', 0.8], ['like', 0.3], ['play', 0.3], ['to', 0.3]]
[['Football', 0.2], ['best', 0.55], ['game', 0.2], ['is', 0.55], ['the', 0.55]]
[['like', 0.17], ['play', 0.17], ['to', 0.17], ['game', 0.17], ['?', 0.47], ['Which', 0.47], ['do', 0.47], ['you', 0.47]]


組み込みの Gensim モデルとデータセットのダウンロード

Gensim には、直接利用できる様々な組み込みデータセットや単語埋め込みモデルが付属しています。

ビルトインモデルやデータセットをダウンロードするには、gensim ライブラリから downloader クラスを使用することができます。

そして、downloaderクラスのloadメソッドを呼び出して、目的のパッケージをダウンロードすることができます。

次のコードを見てください。

import gensim.downloader as api


w2v_embedding = api.load("glove-wiki-gigaword-100")


上記のコマンドで、”glove-wiki-gigaword-100″ word embedding modelをダウンロードします。

このモデルは基本的にWikipediaのテキストをベースにしており、100次元の次元を持つものです。

この単語埋め込みモデルを用いて、”toyota “に類似する単語を検索してみましょう。

以下のコードを使ってください。

w2v_embedding.most_similar('toyota')


出力では、以下のような結果が得られるはずです。

[('honda', 0.8739858865737915),
 ('nissan', 0.8108116984367371),
 ('automaker', 0.7918163537979126),
 ('mazda', 0.7687169313430786),
 ('bmw', 0.7616022825241089),
 ('ford', 0.7547588348388672),
 ('motors', 0.7539199590682983),
 ('volkswagen', 0.7176680564880371),
 ('prius', 0.7156582474708557),
 ('chrysler', 0.7085398435592651)]


すべての結果が “toyota “という単語に非常に関連しているのがわかると思います。

分数内の数字は類似度指数に相当する。

類似度指数が高ければ高いほど、その単語の関連性が高いことを意味する。

結論

Gensimライブラリは、NLP向けのPythonライブラリとして最も人気のあるライブラリの1つです。

この記事では、Gensim ライブラリを使って辞書やコーパスの作成などのタスクを実行する方法を簡単に説明しました。

また、組み込みの Gensim モジュールをダウンロードする方法についても見てきました。

次回は、Gensim ライブラリを使ってトピックモデリングを行う方法について説明します。

タイトルとURLをコピーしました