<jupyter_start><jupyter_text>0. Imports<jupyter_code>import pandas as pd
import gensim
import spacy
from tqdm import tqdm
tqdm.pandas(desc="Progress")
nlp_en = spacy.load("en_core_web_md")<jupyter_output><empty_output><jupyter_text>1. Train word embeddings  1.1 Get data<jupyter_code>pd_data = pd.read_csv("Reviews.csv")
pd_data.head(3)<jupyter_output><empty_output><jupyter_text>1.2. Process data<jupyter_code>def get_tokens(sentence):
    return [x.text for x in nlp_en(sentence)]
pd_data["tokens"] = pd_data["Text"].progress_apply(get_tokens)
pd_data.to_pickle("pd_data_tokenized.pickle")
pd_data = pd.read_pickle("pd_data_tokenized.pickle")<jupyter_output><empty_output><jupyter_text>1.3. Train word embeddings using word2vec<jupyter_code>model_w2v = gensim.models.Word2Vec(pd_data["tokens"].tolist(), min_count=5, window = 9, size = 100)<jupyter_output><empty_output><jupyter_text>1.4. Train word embeddings using fasttext<jupyter_code>model_ft = gensim.models.FastText(pd_data["tokens"].tolist(), min_count=5, window = 9, size = 100)<jupyter_output><empty_output><jupyter_text>1.5. Persistence<jupyter_code>model_w2v.save("model_w2v.model")
model_ft.save("model_ft.model")
model_w2v = gensim.models.Word2Vec.load("model_w2v.model")
model_ft = gensim.models.FastText.load("model_ft.model")<jupyter_output><empty_output><jupyter_text>1.6. Similarity<jupyter_code>model_w2v.most_similar("salmon", topn=5)
model_w2v.most_similar(positive=['cheese'], topn=5)<jupyter_output>C:\Users\peter\Anaconda3\lib\site-packages\ipykernel\__main__.py:1: DeprecationWarning: Call to deprecated `most_similar` (Method will be removed in 4.0.0, use self.wv.most_similar() instead).
  if __name__ == '__main__':<jupyter_text>1.7. Correlation<jupyter_code>model_w2v.most_similar(positive=['pea', 'salsa'], negative=['tomato'], topn=3)
model_w2v.most_similar(positive=['lemon', 'water'], topn=3)
model_w2v.most_similar(positive=['salami', 'crust'], topn=3)
model_w2v.most_similar(positive=['beef', 'bun'], topn=3)<jupyter_output>C:\Users\peter\Anaconda3\lib\site-packages\ipykernel\__main__.py:1: DeprecationWarning: Call to deprecated `most_similar` (Method will be removed in 4.0.0, use self.wv.most_similar() instead).
  if __name__ == '__main__':<jupyter_text>2. Visualise them<jupyter_code>from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource, Range1d, LabelSet, Label
%%time
model_w2v = gensim.models.Word2Vec(pd_data["tokens"].tolist(), min_count=500, window = 9, size = 100)
tokens = []
labels = []

for x in model_w2v.wv.vocab:
    tokens.append(model_w2v[x])
    labels.append(x)
%%time
tsne_model = TSNE(n_components=2, random_state=11)
fitted = tsne_model.fit_transform(tokens)
output_file("plot.html")
            
p = figure(plot_width=1000, plot_height=1000)

lst = list(model_w2v.wv.vocab)



p.circle(fitted[:, 0], fitted[:, 1], size=2, color="navy", alpha=0.5)

texts = lst


source = ColumnDataSource(data=dict(x=fitted[:, 0], y=fitted[:, 1], text=texts))

labels = LabelSet(x='x', y='y', text='text',
         x_offset=5, y_offset=5, source=source)
p.add_layout(labels)



show(p)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1496429680223533, 'fraction_numerical': 0.02825209562247749, 'mean_word_length': 7.779291553133515, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '44365', 'license': 'MIT', 'n_tokens_mistral': 1343, 'n_tokens_neox': 1280, 'n_words': 191, 'path': 'Section5/section5_video3_video4_training_visualizing_wordembedding.ipynb', 'repo_name': 'VonUniGE/Text-Mining-with-Machine-Learning-and-Python', 'size': '3221'}