オリジナルリンク:http://tecdat.cn/?p=8572
この記事では、我々は検討するFastText埋め込み、テキストの分類は非常に便利なモジュールであるため、別の言葉です。
この記事では、我々は簡単にFastTextライブラリについて説明します。この論文は、2つの部分に分割されます。最初の部分では、単語間の意味的な類似性を見つけるために使用することができFastTextライブラリは、ベクトル表現のベクトル表現を作成する方法について説明します。第二部では、我々はテキスト分類におけるアプリケーションFastTextライブラリが表示されます。
セマンティック類似FastText
FastTextサポート単語やスキップ-gramモデルのバッグ。これらのトピックは非常に類似しているため、我々はコーパスを作成するために多くのデータを持っているために、これらのトピックを選んだので、この記事では、我々は、スキップ-gramモデルを実現します。必要に応じて、同様の性質の複数のトピックを追加することができます。
最初のステップは、我々は必要なライブラリをインポートする必要があります。
$ pip install wikipedia
インポートライブラリ
必要なライブラリ我々のアプリケーションをインポートするには、以下のスクリプト:
from keras.preprocessing.text import Tokenizer
from gensim.models.fasttext import FastText
import numpy as np
import matplotlib.pyplot as plt
import nltk
from string import punctuation
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import sent_tokenize
from nltk import WordPunctTokenizer
import wikipedia
import nltk
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('stopwords')
en_stop = set(nltk.corpus.stopwords.words('english'))
%matplotlib inline
ワード表現と意味的な類似性のために、私たちはFastTextためのモデルをGensimすることができます。
Wikipediaの記事
このステップでは、我々は、Wikipediaの記事をクロールする必要があります。次のスクリプトを参照してください。
artificial_intelligence = wikipedia.page("Artificial Intelligence").content
machine_learning = wikipedia.page("Machine Learning").content
deep_learning = wikipedia.page("Deep Learning").content
neural_network = wikipedia.page("Neural Network").content
artificial_intelligence = sent_tokenize(artificial_intelligence)
machine_learning = sent_tokenize(machine_learning)
deep_learning = sent_tokenize(deep_learning)
neural_network = sent_tokenize(neural_network)
artificial_intelligence.extend(machine_learning)
artificial_intelligence.extend(deep_learning)
artificial_intelligence.extend(neural_network)
ウィキペディアのページをクロールするために、我々はモジュールを使用することができますpage
方法をwikipedia
。あなたはに渡されたパラメータとして、ページの名前を切り取って貼り付けるpage
方法。この方法は、返すWikipediaPage
ことで、あなたがオブジェクトを使用することができ、オブジェクトをcontent
上記のスクリプトに示すようなページのコンテンツ属性を取得します。
そして、その使用sent_tokenize
4 Wikipediaのページラベルされた文へのクロール方法からコンテンツを。このsent_tokenize
方法では、文のリストを返します。文4ページは標識されています。最後に、extend
文章にまとめて4件の記事を接続する方法。
データの前処理
次のステップは、句読点や数字を除去することにより、テキストデータをクリアすることです。
preprocess_text
以下の事前定義された関数の実行タスク。
import re
from nltk.stem import WordNetLemmatizer
stemmer = WordNetLemmatizer()
def preprocess_text(document):
preprocessed_text = ' '.join(tokens)
return preprocessed_text
私たちの関数が擬似プレ文で必要なタスクを実行する場合を見てみましょう:
sent = preprocess_text("Artificial intelligence, is the most advanced technology of the present era")
print(sent)
次のように前処理文は次のとおりです。
artificial intelligence advanced technology present
あなたは句読点や停止の単語が削除されているが表示されます。
単語表現を作成します。
私たちは、コーパス前処理しました。今使用することの時間は、言葉の表現を作成FastText。まず、私たちはFastTextスーパーパラメータのモデルを定義してみましょう:
embedding_size = 60
window_size = 40
min_word = 5
down_sampling = 1e-2
これは、embedding_size
埋め込みベクトルの大きさです。
次のパラメータは、スーパーでmin_word
コーパスの最低周波数生成された単語を指定しています、。最後に、最も頻繁に通過出現する単語down_sampling
の属性は、デジタルダウンサンプリングを指定しました。
私たちが今してみましょうFastText
ワード表現モデルを作成することです。
%%time
ft_model = FastText(word_tokenized_corpus,
size=embedding_size,
window=window_size,
min_count=min_word,
sample=down_sampling,
sg=1,
iter=100)
このsg
パラメータは、私たちがモデルを作成したいタイプを定義します。我々はジャンプ文法モデルを作成したい1つの手段の値。ゼロはデフォルトで単語バッグモデルを、指定します。
上記のスクリプトの実装。これは、実行に時間がかかる場合があります。次のように私のマシンでは、統計情報のコード実行時間が次のとおりです。
CPU times: user 1min 45s, sys: 434 ms, total: 1min 45s
Wall time: 57.2 s
print(ft_model.wv['artificial'])
これが出力されます。
[-3.7653010e-02 -4.5558015e-01 3.2035065e-01 -1.5289043e-01
4.0645871e-02 -1.8946664e-01 7.0426887e-01 2.8806925e-01
-1.8166199e-01 1.7566417e-01 1.1522485e-01 -3.6525184e-01
-6.4378887e-01 -1.6650060e-01 7.4625671e-01 -4.8166099e-01
2.0884991e-01 1.8067230e-01 -6.2647951e-01 2.7614883e-01
-3.6478557e-02 1.4782918e-02 -3.3124462e-01 1.9372456e-01
4.3028224e-02 -8.2326338e-02 1.0356739e-01 4.0792203e-01
-2.0596240e-02 -3.5974573e-02 9.9928051e-02 1.7191900e-01
-2.1196717e-01 6.4424530e-02 -4.4705093e-02 9.7391091e-02
-2.8846195e-01 8.8607501e-03 1.6520244e-01 -3.6626378e-01
-6.2017748e-04 -1.5083785e-01 -1.7499258e-01 7.1994811e-02
-1.9868813e-01 -3.1733567e-01 1.9832127e-01 1.2799081e-01
-7.6522082e-01 5.2335665e-02 -4.5766738e-01 -2.7947658e-01
3.7890410e-03 -3.8761377e-01 -9.3001537e-02 -1.7128626e-01
-1.2923178e-01 3.9627206e-01 -3.6673656e-01 2.2755004e-01]
今度は、単語に最も類似し5の「人工」、「スマート」、「機械」、「ネットワーク」、「深さ」を見つけてみましょう「ことが多いです。」あなたは言葉の任意の数を選択することができます。次のスクリプトは、指定した単語と5つの最も類似した単語を印刷します。
for k,v in semantically_similar_words.items():
print(k+":"+str(v))
次のように出力されます。
artificial:['intelligence', 'inspired', 'book', 'academic', 'biological']
intelligence:['artificial', 'human', 'people', 'intelligent', 'general']
machine:['ethic', 'learning', 'concerned', 'argument', 'intelligence']
network:['neural', 'forward', 'deep', 'backpropagation', 'hidden']
recurrent:['rnns', 'short', 'schmidhuber', 'shown', 'feedforward']
deep:['convolutional', 'speech', 'network', 'generative', 'neural']
次のように我々はまた、任意の二つの単語のベクトル間のコサイン類似度を見つけることができます。
print(ft_model.wv.similarity(w1='artificial', w2='intelligence'))
出力は、の値を示し、「0.7481」を この値は、0と1の間とすることができます。より高い値は、類似度が高いことを示します。
可視化ワードの類似性
が各単語のモデルは、60次元のベクトルとして表されるが、我々は2つの主成分を見つけるために、主成分分析を使用することができます。その後、2次元空間に描かれた単語の2つの主要コンポーネントを使用することができます。
print(all_similar_words)
print(type(all_similar_words))
print(len(all_similar_words))
各辞書にはキーワードです。すべての対応する値のリストは、意味的に類似した単語です。私たちは、定期的な「人工」のリストでトップ5最も類似した言葉、「スマート」、「機械」、「ネットワーク」、「」6つのワードの「深さ」を、あなたは見つけることができますので、見つけたので、 30ワードall_similar_words
リスト。
次に、我々は単語ベクトルのすべての30個の単語を検索して、60-2から減少している単語ベクトルの次元にPCAを使用する必要があります。あなたが使用することができるplt
方法を、matplotlib.pyplot
エイリアス方法は、2次元のベクトル空間上の単語を描画する方法です。
単語を視覚化するために、次のスクリプトを実行します。
word_vectors = ft_model.wv[all_similar_words]
for word_names, x, y in zip(word_names, p_comps[:, 0], p_comps[:, 1]):
plt.annotate(word_names, xy=(x+0.06, y+0.03), xytext=(0, 0), textcoords='offset points')
上記出力スクリプトを以下に示します。
私たちは、言葉は、多くの場合、あまりにも互いに近接して2次元平面内のテキストに一緒に表示され見ることができます。
テキスト分類のためのFastText
テキスト分類は、テキストの内容に基づいて事前定義されたカテゴリに分類されたテキストデータを指します。センチメント分析、スパム検出および検出ラベルは、ユースケースのためのテキスト分類の最も一般的な例のいくつかです。
データセット
データセットは、複数のファイルが含まれているが、我々は唯一のですyelp_review.csv
興味のあるファイル。このファイルは、(レストラン、バー、歯科医、医師、美容室などを含む)さまざまなサービスについての520万件のコメントが含まれています。しかし、メモリの制限のため、我々は我々のモデルを訓練するだけ最初の50,000レコードを使用します。必要に応じて、複数のレコードを試すことができます。
私たちは、必要なライブラリをインポートし、データセットをロードしてみましょう:
import pandas as pd
import numpy as np
yelp_reviews = pd.read_csv("/content/drive/My Drive/Colab Datasets/yelp_review_short.csv")
上記のスクリプトでは、我々は、yelp_review_short.csv
使用pd.read_csv
50,000コメントを含むファイルをロードする機能を。
分類に数値を変換することによってコメントは、私たちの問題を簡素化することができます。これは、によるであろうreviews_score
新しい列データの完全な追加します。
最後に、フレームヘッダデータを以下に示します
インストールFastText
次のステップはFastTextモデルは、以下のインポートすることにあるwget
次のスクリプトに示すように、コマンドは、GitHubのリポジトリからコマンドをインポートします。
!wget https://github.com/facebookresearch/fastText/archive/v0.1.0.zip
あなたは上記のスクリプトを実行して、次のような結果が表示された場合、それはFastTextが正常にダウンロードを示します。
--2019-08-16 15:05:05-- https://github.com/facebookresearch/fastText/archive/v0.1.0.zip
Resolving github.com (github.com)... 140.82.113.4
Connecting to github.com (github.com)|140.82.113.4|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://codeload.github.com/facebookresearch/fastText/zip/v0.1.0 [following]
--2019-08-16 15:05:05-- https://codeload.github.com/facebookresearch/fastText/zip/v0.1.0
Resolving codeload.github.com (codeload.github.com)... 192.30.255.121
Connecting to codeload.github.com (codeload.github.com)|192.30.255.121|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [application/zip]
Saving to: ‘v0.1.0.zip’
v0.1.0.zip [ <=> ] 92.06K --.-KB/s in 0.03s
2019-08-16 15:05:05 (3.26 MB/s) - ‘v0.1.0.zip’ saved [94267]
次のステップは、解凍FastTextモジュールです。ただ、次のコマンドを入力します。
!unzip v0.1.0.zip
次に、あなたがFastTextをダウンロードしたディレクトリに移動し、実行しなければならない!make
C ++のバイナリを実行するコマンドを。次の手順を実行します。
cd fastText-0.1.0
!make
あなたは次の出力が表示された場合、それはFastTextが正常にコンピュータにインストールされたことを示します。
c++ -pthread -std=c++0x -O3 -funroll-loops -c src/args.cc
c++ -pthread -std=c++0x -O3 -funroll-loops -c src/dictionary.cc
c++ -pthread -std=c++0x -O3 -funroll-loops -c src/productquantizer.cc
c++ -pthread -std=c++0x -O3 -funroll-loops -c src/matrix.cc
c++ -pthread -std=c++0x -O3 -funroll-loops -c src/qmatrix.cc
c++ -pthread -std=c++0x -O3 -funroll-loops -c src/vector.cc
c++ -pthread -std=c++0x -O3 -funroll-loops -c src/model.cc
c++ -pthread -std=c++0x -O3 -funroll-loops -c src/utils.cc
c++ -pthread -std=c++0x -O3 -funroll-loops -c src/fasttext.cc
c++ -pthread -std=c++0x -O3 -funroll-loops args.o dictionary.o productquantizer.o matrix.o qmatrix.o vector.o model.o utils.o fasttext.o src/main.cc -o fasttext
インストールを確認するには、次のコマンドを実行します。
!./fasttext
あなたはFastTextは、次のコマンドをサポートして表示されるはずです。
usage: fasttext <command> <args>
The commands supported by FastText are:
supervised train a supervised classifier
quantize quantize a model to reduce the memory usage
test evaluate a supervised classifier
predict predict most likely labels
predict-prob predict most likely labels with probabilities
skipgram train a skipgram model
cbow train a cbow model
print-word-vectors print word vectors given a trained model
print-sentence-vectors print sentence vectors given a trained model
nn query for nearest neighbors
analogies query for analogies
テキスト分類
テキスト分類のためのFastTextモデルを訓練する前に、我々は特別な言及を必要とする次のように、データ形式を受け入れるFastText:
_label_tag This is sentence 1
_label_tag2 This is sentence 2.
我々は、データ・セットを見れば、それは形式を希望されていません。次のように肯定的な感情のテキストは次のようになります。
__label__positive burgers are very big portions here.
同様に、否定的なコメントは次のようになります。
__label__negative They do not use organic ingredients, but I thi...
次のスクリプトは、データセットからろ過しreviews_score
そしてtext
カラム、次いで、すべての列の値の前に追加の接頭辞。同様に、とによって列空間を交換します。最後に、更新されたデータは、フレームの形で書かれています。__label__
reviews_score
\n
\t
text
yelp_reviews_updated.txt
import pandas as pd
from io import StringIO
import csv
col = ['reviews_score', 'text']
今度は更新印刷させyelp_reviews
たデータボックスを。
yelp_reviews.head()
次のような結果が表示されます。
reviews_score text
0 __label__positive Super simple place but amazing nonetheless. It...
1 __label__positive Small unassuming place that changes their menu...
2 __label__positive Lester's is located in a beautiful neighborhoo...
3 __label__positive Love coming here. Yes the place always needs t...
4 __label__positive Had their chocolate almond croissant and it wa...
以下同様に、データフレームの末尾です。
reviews_score text
49995 __label__positive This is an awesome consignment store! They hav...
49996 __label__positive Awesome laid back atmosphere with made-to-orde...
49997 __label__positive Today was my first appointment and I can hones...
49998 __label__positive I love this chic salon. They use the best prod...
49999 __label__positive This place is delicious. All their meats and s...
私たちは、所望の形状にデータセットを変換する必要があります。次のステップは、トレーニングとテストセットに我々のデータです。トレーニングデータのためのデータの80%(すなわち、前50,000レコードに40,000を記録する)、データ(最後10,000レコード)の20%は、アルゴリズムの性能を評価するために使用されています。
トレーニングとテストセットに次のスクリプトデータ:
!head -n 40000 "/content/drive/My Drive/Colab Datasets/yelp_reviews_updated.txt" > "/content/drive/My Drive/Colab Datasets/yelp_reviews_train.txt"
!tail -n 10000 "/content/drive/My Drive/Colab Datasets/yelp_reviews_updated.txt" > "/content/drive/My Drive/Colab Datasets/yelp_reviews_test.txt"
yelp_reviews_train.txt
これは、トレーニングデータを含むファイルを生成します。同様に、新世代のyelp_reviews_test.txt
ファイルは、テスト・データが含まれています。
今私達のFastTextテキスト分類アルゴリズムを訓練する時間があります。
%%time
!./fasttext supervised -input "/content/drive/My Drive/Colab Datasets/yelp_reviews_train.txt" -output model_yelp_reviews
アルゴリズムを訓練するために、我々は使用する必要がありsupervised
、コマンドを入力して、ファイルに渡します。これは、上記のスクリプトの出力です:
Read 4M words
Number of words: 177864
Number of labels: 2
Progress: 100.0% words/sec/thread: 2548017 lr: 0.000000 loss: 0.246120 eta: 0h0m
CPU times: user 212 ms, sys: 48.6 ms, total: 261 ms
Wall time: 15.6 s
あなたは、次の使用できる!ls
ビューモデルのコマンドを:
!ls
これが出力されます。
args.o Makefile quantization-results.sh
classification-example.sh matrix.o README.md
classification-results.sh model.o src
CONTRIBUTING.md model_yelp_reviews.bin tutorials
dictionary.o model_yelp_reviews.vec utils.o
eval.py PATENTS vector.o
fasttext pretrained-vectors.md wikifil.pl
fasttext.o productquantizer.o word-vector-example.sh
get-wikimedia.sh qmatrix.o yelp_reviews_train.txt
LICENSE quantization-example.sh
あなたはできるmodel_yelp_reviews.bin
上記のドキュメントの一覧に表示されます。
最後に、あなたは次のように使用できるtest
モデルをテストするためのコマンドを。必要がありtest
、次のように、モデル名とテストファイルのコマンドを指定します。
!./fasttext test model_yelp_reviews.bin "/content/drive/My Drive/Colab Datasets/yelp_reviews_test.txt"
上記出力スクリプトを以下に示します。
N 10000
P@1 0.909
R@1 0.909
Number of examples: 10000
本明細書では、P@1
精度を指し、R@1
それはリコールを指します。あなたは私たちのモデルはかなり良いです0.909精度と再現率に達し、見ることができます。
さて、聞かせてのは、テキストの一貫性を改善するために、文字を小文字に明確な句読点やテキストと変換しての特殊文字にしてみてください。
!cat "/content/drive/My Drive/Colab Datasets/yelp_reviews_train.txt" | sed -e "s/\([.\!?,’/()]\)/ \1 /g" | tr "[:upper:]" "[:lower:]" > "/content/drive/My Drive/Colab Datasets/yelp_reviews_train_clean.txt"
そして、次のスクリプトは、テストセットをクリアするには:
"/content/drive/My Drive/Colab Datasets/yelp_reviews_test.txt" | sed -e "s/\([.\!?,’/()]\)/ \1 /g" | tr "[:upper:]" "[:lower:]" > "/content/drive/My Drive/Colab Datasets/yelp_reviews_test_clean.txt"
今、私たちは、クリーンアップのトレーニングセットにモデルをトレーニングします。
%%time
!./fasttext supervised -input "/content/drive/My Drive/Colab Datasets/yelp_reviews_train_clean.txt" -output model_yelp_reviews
最後に、私たちは浄化テストセット予測のためのトレーニングセットで訓練モデルを使用します。
!./fasttext test model_yelp_reviews.bin "/content/drive/My Drive/Colab Datasets/yelp_reviews_test_clean.txt"
次のように上記のスクリプトの出力は次のようになります。
N 10000
P@1 0.915
R@1 0.915
Number of examples: 10000
あなたは、精度と再現率がわずかに増加しているが表示されます。さらにモデルを改善するには、時間と学習速度モデルを増やすことができます。30次のスクリプトメタデータセットは、学習率は0.5に設定されています。
%%time
!./fasttext supervised -input "/content/drive/My Drive/Colab Datasets/yelp_reviews_train_clean.txt" -output model_yelp_reviews -epoch 30 -lr 0.5
結論
最近、それは証明されているFastTextモデルは、多くのデータ・セットやテキスト分類タスクの単語を挿入するために使用することができます。モデルに組み込まれた他の言葉と比較すると、それは非常に使いやすいと超高速です。
ご質問があれば、以下のコメントを残してください。
ビッグデータの部族 -中国のプロのサードパーティのデータ・サービス・プロバイダは、ワンストップのデータマイニングや統計解析コンサルティングサービスを提供するために、カスタマイズされました
コンサルティングサービス統計解析やデータマイニング:y0.cn/teradat(コンサルティングサービスは、お問い合わせください公式サイトの顧客サービスを)
[サービス]シーン
研究;会社アウトソーシング、オンラインとオフラインの1のトレーニング、データ爬虫類の収集、学術研究、報告書作成、市場調査。
[トライブ]ビッグデータは、カスタマイズ提供するワンストップのデータマイニングや統計解析コンサルティング
私たちの選択科目へようこそ採掘が知っているだろうR言語データ解析をコースを!
ビッグデータの部族 -中国のプロのサードパーティのデータ・サービス・プロバイダは、ワンストップのデータマイニングや統計解析コンサルティングサービスを提供するために、カスタマイズされました
コンサルティングサービス統計解析やデータマイニング:y0.cn/teradat(コンサルティングサービスは、お問い合わせください公式サイトの顧客サービスを)
[サービス]シーン
研究;会社アウトソーシング、オンラインとオフラインの1のトレーニング、データ爬虫類の収集、学術研究、報告書作成、市場調査。
[トライブ]ビッグデータは、カスタマイズ提供するワンストップのデータマイニングや統計解析コンサルティング
私たちの選択科目へようこそ採掘が知っているだろうR言語データ解析をコースを!