NLP Feature Engineering #2
Solution for submission 171870
A detailed solution for submission 171870 submitted for challenge NLP Feature Engineering #2
Starter Code for NLP Feature Engineering #2
What we are going to Learn¶
- How to convert your text into numbers ?
- How Bag of words, TF-IDF works ?
- Testing and Submitting the Results to the Challenge.
About this Challanges¶
Now, this challange is very different form what we usually do in AIcrowd Blitz.In this challanges, the task is to generate features from a text data. Extracting features helps up to generate text embeddings will contains more useful information about the text.
Setup AIcrowd Utilities 🛠¶
We use this to bundle the files for submission and create a submission on AIcrowd. Do not edit this block.
!pip install -q -U aicrowd-cli
%load_ext aicrowd.magic
How to use this notebook? 📝¶
- Update the config parameters. You can define the common variables here
Variable | Description |
---|---|
AICROWD_DATASET_PATH |
Path to the file containing test data (The data will be available at /data/ on aridhia workspace). This should be an absolute path. |
AICROWD_OUTPUTS_PATH |
Path to write the output to. |
AICROWD_ASSETS_DIR |
In case your notebook needs additional files (like model weights, etc.,), you can add them to a directory and specify the path to the directory here (please specify relative path). The contents of this directory will be sent to AIcrowd for evaluation. |
AICROWD_API_KEY |
In order to submit your code to AIcrowd, you need to provide your account's API key. This key is available at https://www.aicrowd.com/participants/me |
- Installing packages. Please use the Install packages 🗃 section to install the packages
- Training your models. All the code within the Training phase ⚙️ section will be skipped during evaluation. Please make sure to save your model weights in the assets directory and load them in the predictions phase section
AIcrowd Runtime Configuration 🧷¶
Define configuration parameters. Please include any files needed for the notebook to run under ASSETS_DIR
. We will copy the contents of this directory to your final submission file 🙂
The dataset is available under /data
on the workspace.
import os
# Please use the absolute for the location of the dataset.
# Or you can use relative path with `os.getcwd() + "test_data/test.csv"`
AICROWD_DATASET_PATH = os.getenv("DATASET_PATH", os.getcwd()+"/data/data.csv")
AICROWD_OUTPUTS_PATH = os.getenv("OUTPUTS_DIR", "")
AICROWD_ASSETS_DIR = os.getenv("ASSETS_DIR", "assets")
Install packages 🗃¶
We are going to use many different libraries to demonstrate many idfferent techniques to convert text into numbers ( or more specifically vectors )
!pip install --upgrade spacy rich gensim tensorflow scikit-learn
!python -m spacy download en_core_web_sm # Downloaing the model for english language will contains many pretrained preprocessing pipelines
Define preprocessing code 💻¶
The code that is common between the training and the prediction sections should be defined here. During evaluation, we completely skip the training section. Please make sure to add any common logic between the training and prediction sections here.
# Importing Libraries
import pandas as pd
import numpy as np
np.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning)
import random
from tqdm.notebook import tqdm
import unicodedata
import re
# Tensorflow
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Sklearn
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score, accuracy_score
# Word2vec Implementation
import spacy
nlp = spacy.load('en_core_web_sm', exclude=['tagger', 'ner', 'attribute_ruler', 'lemmatizer'])
from gensim.models import Word2Vec
from gensim.models.phrases import Phrases, Phraser
# To make things more beautiful!
from rich.console import Console
from rich.table import Table
from rich.segment import Segment
from rich import pretty
pretty.install()
# Seeding everything for getting same results
random.seed(42)
np.random.seed(42)
# function to display YouTube videos
from IPython.display import YouTubeVideo
# Latest version of gensim
import gensim
gensim.__version__
# Defining the function for preprocessing test dataset which will run after submitting the notebook
def tokenize_sentence(sentences, num_words=10000, maxlen=256, show=False):
# Creating the tokenizer, the num_words represents the vocabulary and assigning OOV token ( out of vocaculary ) for unknown token
# Which can arise if we input a sentence containing a words that tokenizer don't have in his vocabulary
tokenizer = Tokenizer(num_words=num_words, oov_token="<OOV>")
tokenizer.fit_on_texts(sentences)
# Getting the unique ID for each token
word_index = tokenizer.word_index
# Convert the sentences into vector
sequences = tokenizer.texts_to_sequences(sentences)
# Padding the vectors so that all vectors have the same length
padded_sequences = pad_sequences(sequences, padding='post', truncating='pre', maxlen=maxlen)
word_index = np.asarray(word_index)
sequences = np.asarray(sequences)
padded_sequences = np.asarray(padded_sequences)
if show==True:
console = Console()
console.log("Word Index. A unique ID is assigned to each token.")
console.log(word_index)
console.log("---"*10)
console.log("Sequences. senteces converted into vector.")
console.log(np.array(sequences[0]))
console.log("---"*10)
console.log("Padded Sequences. Adding,( 0 in this case ) or removing elements to make all vectors in the samples same.")
console.log(np.array(padded_sequences[0]))
console.log("---"*10)
return tokenizer, word_index, sequences, padded_sequences
Training phase ⚙️¶
You can define your training code here. This sections will be skipped during evaluation.
Downloading Dataset¶
Must be pretty familar thing by now :) In case, here we are downloading the challange dataset using AIcrowd CLI
%aicrowd login
# Downloading the Dataset
!mkdir data
# Donwloading programming language classification dataset for testing purposes
!mkdir programming-language-data
Reading Dataset¶
Reading the necessary files to train, validation & submit our results!
We are also using Programming Language Challange dataset for testing purposes.
dataset = pd.read_csv("data/data.csv")
train_data = pd.read_csv("programming-language-data/train.csv")
dataset
Creating our Templete¶
So, with this train_model
we are going to test the various different techniques and compare to see which works best!
def train_model(X, y):
# Splitting the dataset into training and testing, also by using stratify, we are making sure to use the same class balance between training and testing.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
# Creating and training sklearn's Decision Tree Classifier Model
# clf = DecisionTreeClassifier(random_state=42)
clf = RandomForestClassifier(random_state=42)
clf.fit(X_train, y_train)
# Getting the predictions form unseen (testing dataset)
predictions = clf.predict(X_test)
# Calcuating the metrics
f1 = f1_score(y_test, predictions, average='weighted')
accuracy = accuracy_score(y_test, predictions)
# Creating the table
console = Console()
result_table = Table(show_header=False, header_style="bold magenta")
result_table.add_row("F1 Score", str(f1))
result_table.add_row("Accuracy Score", str(accuracy))
# Showing the table
console.print(result_table)
return f1, accuracy
Simple Tokenization 🪙¶
Here, all what we are doing is splitting the sentences into tokens/words, and then assigning a unique id to each token, and here we go, we converted the text into a vector. We are also using padding to make sure all vectors are of maxlen
which is 256.
def tokenize_sentence(sentences, num_words=10000, maxlen=256, show=False):
# Creating the tokenizer, the num_words represents the vocabulary and assigning OOV token ( out of vocaculary ) for unknown tokenn
# Which can arise if we input a sentence containing a words that tokenizer don't have in his vocabulary
tokenizer = Tokenizer(num_words=num_words, oov_token="<OOV>")
tokenizer.fit_on_texts(sentences)
# Getting the unique ID for each token
word_index = tokenizer.word_index
# Convert the senteces into vector
sequences = tokenizer.texts_to_sequences(sentences)
# Padding the vectors so that all vectors have the same length
padded_sequences = pad_sequences(sequences, padding='post', truncating='pre', maxlen=maxlen)
word_index = np.asarray(word_index)
sequences = np.asarray(sequences)
padded_sequences = np.asarray(padded_sequences)
if show==True:
console = Console()
console.log("Word Index. A unique ID is assigned to each token.")
console.log(word_index)
console.log("---"*10)
console.log("Sequences. senteces converted into vector.")
console.log(np.array(sequences[0]))
console.log("---"*10)
console.log("Padded Sequences. Adding,( 0 in this case ) or removing elements to make all vectors in the samples same.")
console.log(np.array(padded_sequences[0]))
console.log("---"*10)
return tokenizer, word_index, sequences, padded_sequences
# Sample Senteces
sample_sentences = dataset.iloc[0, 1].split(".")
sample_sentences
_, _, _, _ = tokenize_sentence(sample_sentences, num_words=50, maxlen=16, show=True)
# Training the model using the vectors and the features
tokenizer, _, _, X = tokenize_sentence(train_data['code'].values)
y = train_data['language'].values
print("Sentence : ", train_data['code'][2])
print("Simple Tokenizer : ", X[2])
token_id_f1, token_id_accuracy = train_model(X, y)
Now, the advantages of this method is that it is very simple, but one of the major disadvantages for this is it doesn't contain the "meaning" of the text, and mny next will also not be able to solve this issue, unzip word2vec
Bag of Words 🎒¶
In Bag of Words, instead of what we did in simple tokenization, just assiging a unique ID to each token, bag of words, does things a little different.
I find bag of words harder to understand with a text, so i find this video really helpful for understand bag of words in a more visual way. Be sure to watch it.
tokenizer, _, _, _ = tokenize_sentence(train_data['code'].values, num_words=256)
X = tokenizer.texts_to_matrix(train_data['code'].values)
print("Sentence : ", train_data['code'][0])
print("BOW : ", X[0])
bow_f1, bow_accuracy = train_model(X, y)
Yee! both of the metrics did increased! Advantages of Bag of words is that it's again, really simple, but it doesn't keep the same order of words in sentence and doesn't keep the meaning of the sentence.
Count Vectorization 🔢¶
Count Vectorization is also very similar to Bag of Wards but instead of one hot, it also include the count of each token in a sentece.
tokenizer, _, _, _ = tokenize_sentence(train_data['code'].values, num_words=256)
X = tokenizer.texts_to_matrix(train_data['code'].values, mode='count')
print("Sentence : ", train_data['code'][2])
print("CV : ", X[2])
count_f1, count_accuracy = train_model(X, y)
TF - IDF 📐¶
TF-IDF is Term Frequency - Inverse Document Frequency. So as we way in last section, about count frequency, that had a bit of flaw, for ex. tokens such a is, are, the
are very common and will generally have bigger counts, but they don't ususally help for ex. classify whether the text is positive or negative. TF-IDF actually try to solve this issue. TF-IDF applies lower score to the common tokens and higher scores for more rarer tokens.
tokenizer, _, _, _ = tokenize_sentence(train_data['code'].values, num_words=256)
X = tokenizer.texts_to_matrix(train_data['code'].values, mode='tfidf')
print("Sentence : ", train_data['code'][0])
print("TF-IDF : ", X[0])
tfidf_f1, tfidf_accuracy = train_model(X, y)
Prediction phase 🔎¶
Generating the features in test dataset.
test_dataset = pd.read_csv(AICROWD_DATASET_PATH)
test_dataset
#import nltk
#from nltk.corpus import stopwords
#nltk.download('stopwords')
# Turn a Unicode string to plain ASCII, thanks to
# https://stackoverflow.com/a/518232/2809427
def unicodeToAscii(s):
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn'
)
# Lowercase, trim, and remove non-letter characters
def normalizeString(s):
s = unicodeToAscii(s.lower().strip())
s = re.sub(r"([.!?])", r" \1", s)
s = re.sub(r"[^a-zA-Z.!?]+", r" ", s)
s = s.replace('?', '')
# s = " ".join([word for word in s.split(' ') if word not in stopwords.words('english')])
return s
test_dataset['text2'] = test_dataset['text'].apply(lambda x: normalizeString(x))
# So, let's do a simple tokenization and generate the features!
# _, _, _, X = tokenize_sentence(test_dataset['text'].values)
tokenizer, _, _, _ = tokenize_sentence(test_dataset['text2'].values, num_words=256)
X = tokenizer.texts_to_matrix(test_dataset['text'].values, mode='count')
for index, row in tqdm(test_dataset.iterrows()):
test_dataset.iloc[index, 2] = str(X[index].tolist())
test_dataset
# Saving the sample submission
test_dataset.to_csv(os.path.join(AICROWD_OUTPUTS_PATH,'submission.csv'), index=False)
Submit to AIcrowd 🚀¶
Note : Please save the notebook before submitting it (Ctrl + S)
%aicrowd notebook submit --assets-dir $AICROWD_ASSETS_DIR --challenge nlp-feature-engineering-2 --no-verify
Congratulations 🎉 you did it, but there still a lot of improvement that can be made, this is feature engineering challange after all, means that we have to fit as much information as we can about the text in 256
numbers. We only covered converting texts into vector, but there are so many things you can try more, for ex. unsupervised classification, idk, maybe it can help :)
And btw -
Don't be shy to ask question related to any errors you are getting or doubts in any part of this notebook in discussion forum or in AIcrowd Discord sever, AIcrew will be happy to help you :)
Also, wanna give us your valuable feedback for next blitz or wanna work with us creating blitz challanges ? Let us know!
Content
Comments
You must login before you can post a comment.