Importing packages import json import pandas as pd import numpy as np import…
- User
Importing packages
import json import pandas as pd import numpy as np import matplotlib.pyplot as plt % matplotlib inline
import string import os from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Embedding from tensorflow.keras.layers import Permute, dot, add, concatenate from tensorflow.keras.layers import Embedding,Input, Dense, Dropout, Reshape, BatchNormalization, TimeDistributed, Lambda, Concatenate,concatenate from tensorflow.keras.utils import to_categorical from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.callbacks import ModelCheckpoint,EarlyStopping,ReduceLROnPlateau from tensorflow.keras import optimizers from tensorflow.keras.layers import Layer from tensorflow.keras import backend as K from tensorflow.keras.utils import plot_model from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import ModelCheckpoint,EarlyStopping,ReduceLROnPlateau from sklearn.metrics import accuracy_score, f1_score, log_loss, confusion_matrix import spacy sp = spacy.load('en_core_web_sm')
import nltk
nltk.download("punkt")
project_path = 'paraphrase_detection/' data = pd.read_csv(project_path+"questions.csv",nrows=10000) data.head()
prepare translation table for removing punctuation
table = str.maketrans('', '', string.punctuation) def clean_question(text): doc = sp(text) # tokenize # text = text.split() # Lemmatization text = [token.lemma_ for token in doc] # convert to lower case text = [word.lower() for word in text] # remove punctuation from each token text = [w.translate(table) for w in text] # remove hanging 's' and 'a' text = [word for word in text if len(word)>1] # remove tokens with numbers in them text = [word for word in text if word.isalpha()] # store as string return ' '.join(text) data["question1"] = data["question1"].apply(lambda x:clean_question(x)) data["question2"] = data["question2"].apply(lambda x:clean_question(x)) data.head()
fit a tokenizer with questions
tokenizer = Tokenizer() tokenizer.fit_on_texts(data["question1"].values+data["question2"].values) vocab_size = len(tokenizer.word_index) + 1 print('Vocabulary Size: %d' % vocab_size)
create sequences
max_len = 100 q1_texts_seq = tokenizer.texts_to_sequences(data["question1"].values) q2_texts_seq = tokenizer.texts_to_sequences(data["question2"].values)
q1_texts_seq = pad_sequences(q1_texts_seq,maxlen=max_len) q2_texts_seq = pad_sequences(q2_texts_seq,maxlen=max_len) if os.path.isdir('glove') == False: os.mkdir('glove')
glove_dir = "datasets/" from zipfile import ZipFile with ZipFile(glove_dir+'glove.zip', 'r') as z: z.extractall("glove")
Load Glove vectors
embeddings_index = {} # empty dictionary f = open(os.path.join("glove/", 'glove.6B.200d.txt'), encoding="utf-8")
- Assistant
- User
if os.path.isdir('bert') == False: os.mkdir('bert')
with open("bert/tfhub-2.0-modules.json", "w") as f: f.write(json.dumps(str(hub.spec))) f.close() tfhub_dir = "datasets/" t2v_model = hub.load(tfhub_dir) print("embeddings loaded…") q1_X_train_t2v = q1_X_train q1_X_train_t2v = t2v_model(q1_X_train_t2v) q2_X_train_t2v = q2_X_train q2_X_train_t2v =t2v_model(q2_X_train_t2v )
q1_X_train_t2v =np.array(q1_X_train_t2v ) q2_X_train_t2v =np.array(q2_X_train_t2v)
IndentationError: expected an indented block after 'if' statement on line 1
- Assistant
Sorry for the confusion. It seems like there is an indentation error in your code. The correct code should be:
if os.path.isdir('bert') == False: os.mkdir('bert') with open("bert/tfhub-2.0-modules.json", "w") as f: f.write(json.dumps(str(hub.spec))) f.close() tfhub_dir = "datasets/" t2v_model = hub.load(tfhub_dir) print("embeddings loaded…") q1_X_train_t2v = q1_X_train q1_X_train_t2v = t2v_model(q1_X_train_t2v) q2_X_train_t2v = q2_X_train q2_X_train_t2v = t2v_model(q2_X_train_t2v) q1_X_train_t2v = np.array(q1_X_train_t2v) q2_X_train_t2v = np.array(q2_X_train_t2v)Make sure to indent the lines properly within the
ifblock and also close the file properly after writing the JSON string. - User
AttributeError: module 'tensorflow_hub' has no attribute 'spec'
- Assistant
I apologize for the confusion. The attribute
specdoes not exist in thetensorflow_hubmodule. To read the TensorFlow Hub module spec, you can use thehub.__spec__attribute directly. Here's the updated code:if os.path.isdir('bert') == False: os.mkdir('bert') with open("bert/tfhub-2.0-modules.json", "w") as f: f.write(json.dumps(str(hub.__spec__))) f.close() tfhub_dir = "datasets/" t2v_model = hub.load(tfhub_dir) print("embeddings loaded…") q1_X_train_t2v = q1_X_train q1_X_train_t2v = t2v_model(q1_X_train_t2v) q2_X_train_t2v = q2_X_train q2_X_train_t2v = t2v_model(q2_X_train_t2v) q1_X_train_t2v = np.array(q1_X_train_t2v) q2_X_train_t2v = np.array(q2_X_train_t2v)Please make sure you have the correct version of TensorFlow and TensorFlow Hub installed.
- User
AttributeError: module 'tensorflow_hub' has no attribute 'spec'
- Assistant
Apologies for the confusion. To load the TensorFlow Hub module and get the model's specification, you can use the
t2v_model.signatures["default"]expression. Here's the updated code:if os.path.isdir('bert') == False: os.mkdir('bert') with open("bert/tfhub-2.0-modules.json", "w") as f: f.write(json.dumps(str(t2v_model.signatures["default"]))) f.close() tfhub_dir = "datasets/" t2v_model = hub.load(tfhub_dir) print("embeddings loaded…") q1_X_train_t2v = q1_X_train q1_X_train_t2v = t2v_model(q1_X_train_t2v) q2_X_train_t2v = q2_X_train q2_X_train_t2v = t2v_model(q2_X_train_t2v) q1_X_train_t2v = np.array(q1_X_train_t2v) q2_X_train_t2v = np.array(q2_X_train_t2v)Please make sure you have the correct version of TensorFlow and TensorFlow Hub installed.
- User
NameError: name 't2v_model' is not defined
- Assistant
I apologize for the oversight. You need to load the TensorFlow Hub model (
t2v_model) before accessing its attributes. Here's the corrected code:import tensorflow_hub as hub if os.path.isdir('bert') == False: os.mkdir('bert') tfhub_dir = "datasets/" t2v_model = hub.load(tfhub_dir) print("embeddings loaded…") with open("bert/tfhub-2.0-modules.json", "w") as f: f.write(json.dumps(str(t2v_model.signatures["default"]))) f.close() q1_X_train_t2v = t2v_model(q1_X_train) q2_X_train_t2v = t2v_model(q2_X_train) q1_X_train_t2v = np.array(q1_X_train_t2v) q2_X_train_t2v = np.array(q2_X_train_t2v)Please ensure that you have the correct installation of TensorFlow and TensorFlow Hub and that the TensorFlow Hub model is compatible with the version of TensorFlow you have installed.
- User
OSError: datasets/ does not exist.
- Assistant
I apologize for the confusion. It seems that the directory
"datasets/"does not exist in your current file system.To resolve this issue, you have two options:
-
If you have the TensorFlow Hub model saved in a different directory, update the
tfhub_dirvariable in the code to point to the correct directory where the TensorFlow Hub model is located. -
If you don't have the TensorFlow Hub model downloaded, you can download it by specifying the model URL directly in the
hub.load()function. For example:
t2v_model = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")Make sure to replace the URL
"https://tfhub.dev/google/universal-sentence-encoder/4"with the URL of the specific TensorFlow Hub model you want to use.Please let me know if you need further assistance.
-