# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: 'Python 3.8.3 64-bit (''base'': conda)'
#     name: python3
# ---

# ### Word to Vec

# +
# #! pip install plotly_express
# -

import gensim

OHCO = ['book_id', 'chap_num', 'para_num', 'sent_num', 'token_num']
BAG = OHCO[:4] # Paragraphs
# BAG = OHCO[:5] # Sentences
window = 5

import pandas as pd
import numpy as np
from gensim.models import word2vec
from sklearn.manifold import TSNE
import plotly_express as px

# %matplotlib inline

LIB = pd.read_csv('LIB.csv')

for i in LIB['book_title']:
    if 'Austen' in i:
        print(i)

# +
aus_books = []
for i in LIB.iterrows():
    if 'austen' in i[1][3]:
        aus_books.append(i[1][0])

    
# -

aus_books

TOKENS = pd.read_csv('TOKEN2.csv')

t1=TOKENS

corpus1 = t1[~t1.pos.str.match('NNPS?')]\
    .groupby(BAG)\
    .term_str.apply(lambda  x:  x.tolist())\
    .reset_index()['term_str'].tolist()


m1 = word2vec.Word2Vec(corpus1, window=window, min_count=200, workers=4)

# coords = pd.DataFrame(index=range(len(model.wv)))
# coords['label'] = [w for w in model.wv]
# coords['vector'] = coords['label'].apply(lambda x: model.wv.get_vector(x))
coords1 = pd.DataFrame(index=range(len(m1.wv.key_to_index)))
coords1['label'] = m1.wv.index_to_key
coords1['vector'] = coords1['label'].apply(lambda x: m1.wv.get_vector(x))

tsne_model1 = TSNE(perplexity=40, n_components=2, init='pca', n_iter=2500, random_state=23)
tsne_values1 = tsne_model1.fit_transform(coords1['vector'].tolist())

coords1['x'] = tsne_values1[:,0]
coords1['y'] = tsne_values1[:,1]
coords1.head()

px.scatter(coords1, 'x', 'y', text='label', height=1000, title='Jane Austen Word Plot').update_traces(mode='text')


def complete_analogy_1(A, B, C, n=2):
    try:
        return m1.wv.most_similar(positive=[B, C], negative=[A])[0:n]
    except KeyError as e:
        print('Error:', e)
        return None


complete_analogy_1('mother', 'herself', 'father')

complete_analogy_1('sister', 'me', 'brother')

complete_analogy_1('you', 'thought', 'me')



StarcoderdataJupyterScriptsDedupFiltered