В этом посте мы увидим, как генерировать встраивания слов и строить диаграммы для соответствующих слов.
Зависимости
- NLTK - Sklearn - Gensim - Plotly - Pandas
Сначала нам нужно получить абзац или текст, для которого нужно найти эмбеддинги, для этого поста я взял праграф отсюда.
paragraph = '''Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter. When viewed from Earth, Jupiter can be bright enough for its reflected light to cast shadows, and is on average the third-brightest natural object in the night sky after the Moon and Venus.'''
Далее нам нужно токенизировать текст, поэтому для этого мы используем библиотеку nltk
:
import nltk # tokeninizing the paragraph sent_text = nltk.sent_tokenize(paragraph) word_text = [nltk.word_tokenize(sent) for sent in sent_text] print(word_text)
После токенизации мы получим 2D-массив, который будет выглядеть следующим образом:
[['Jupiter', 'is', 'the', 'fifth', 'planet', 'from', 'the', 'Sun', 'and', 'the', 'largest', 'in', 'the', 'Solar', 'System', '.'], ['It', 'is', 'a', 'gas', 'giant', 'with', 'a', 'mass', 'one-thousandth', 'that', 'of', 'the', 'Sun', ',', 'but', 'two-and-a-half', 'times', 'that', 'of', 'all', 'the', 'other', 'planets', 'in', 'the', 'Solar', 'System', 'combined', '.'], ['Jupiter', 'is', 'one', 'of', 'the', 'brightest', 'objects', 'visible', 'to', 'the', 'naked', 'eye', 'in', 'the', 'night', 'sky', ',', 'and', 'has', 'been', 'known', 'to', 'ancient', 'civilizations', 'since', 'before', 'recorded', 'history', '.'], ['It', 'is', 'named', 'after', 'the', 'Roman', 'god', 'Jupiter', '.'], ['When', 'viewed', 'from', 'Earth', ',', 'Jupiter', 'can', 'be', 'bright', 'enough', 'for', 'its', 'reflected', 'light', 'to', 'cast', 'shadows', ',', 'and', 'is', 'on', 'average', 'the', 'third-brightest', 'natural', 'object', 'in', 'the', 'night', 'sky', 'after', 'the', 'Moon', 'and', 'Venus', '.']]
Теперь мы будем использовать пакет gensim
для получения встраивания слов из модели Word2Vec
.
from gensim.models import Word2Vec # train model to get the embeddings model = Word2Vec(word_text, min_count=1)
Чтобы построить вложения слов, нам нужно сначала преобразовать многомерные вложения в двумерный массив. Итак, чтобы преобразовать его в 2D-массив, мы используем PCA
# getting the embedding vectors X = model[model.wv.vocab] # dimentionality reduction using PCA pca = PCA(n_components=2) # running the transformations result = pca.fit_transform(X) # getting the corresponding words words = list(model.wv.vocab)
Нам нужно выполнить некоторую обработку, чтобы преобразовать результаты PCA в фрейм данных, и она выглядит следующим образом:
import pandas as pd # creating a dataframe from the results df = pd.DataFrame(result, columns=list('XY')) # adding a columns for the corresponding words df['Words'] = words # converting the lower case text to title case df['Words'] = df['Words'].str.title()
После получения необходимого массива мы можем построить график, используя plotly
import plotly.express as px # plotting a scatter plot fig = px.scatter(df, x="X", y="Y", text="Words", log_x=True, size_max=60) # adjusting the text position fig.update_traces(textposition='top center') # setting up the height and title fig.update_layout( height=600, title_text='Word embedding chart' ) # displaying the figure fig.show()
Теперь диаграмма встраивания слов будет выглядеть следующим образом:
Весь код выглядит следующим образом:
import nltk import pandas as pd import plotly.express as px from gensim.models import Word2Vec paragraph = '''Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter. When viewed from Earth, Jupiter can be bright enough for its reflected light to cast shadows, and is on average the third-brightest natural object in the night sky after the Moon and Venus.''' # tokeninizing the paragraph sent_text = nltk.sent_tokenize(paragraph) word_text = [nltk.word_tokenize(sent) for sent in sent_text] # train model to get the embeddings model = Word2Vec(word_text, min_count=1) # getting the embedding vectors X = model[model.wv.vocab] # dimentionality reduction using PCA pca = PCA(n_components=2) # running the transformations result = pca.fit_transform(X) # getting the corresponding words words = list(model.wv.vocab) # creating a dataframe from the results df = pd.DataFrame(result, columns=list('XY')) # adding a columns for the corresponding words df['Words'] = words # converting the lower case text to title case df['Words'] = df['Words'].str.title() # plotting a scatter plot fig = px.scatter(df, x="X", y="Y", text="Words", log_x=True, size_max=60) # adjusting the text position fig.update_traces(textposition='top center') # setting up the height and title fig.update_layout( height=600, title_text='Word embedding chart' ) # displaying the figure fig.show()
Удачного кодирования!!!