NLP Feature Engineering
Solution for submission 146912
A detailed solution for submission 146912 submitted for challenge NLP Feature Engineering
Solution for NLP Feature Engineering LB: 0.781¶
This solution consists utilises a count vectorizer and a TF IDF as feature engineering.
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
# import nltk
# 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 sklearn to do Count Vectorization and TF IDF.
!pip install --upgrade scikit-learn
!pip install -q -U aicrowd-cli
! pip install nltk
import nltk
nltk.download('punkt')
nltk.download('wordnet')
# ! pip install clean-text
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.
from glob import glob
import os
import pandas as pd
import numpy as np
# from sklearn import model_selection
# from sklearn.tree import DecisionTreeClassifier
# from sklearn.model_selection import train_test_split
# from sklearn.metrics import f1_score, accuracy_score
import sklearn
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.stem import PorterStemmer
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
porter=PorterStemmer()
Training phase ⚙️¶
You can define your training code here. This sections will be skipped during evaluation.
For this solution approach there is no training needed! π
# Downloading the Dataset
!mkdir data
Prediction phase 🔎¶
Generating the features in test dataset.
test_dataset = pd.read_csv(AICROWD_DATASET_PATH)
test_dataset
Count Vectorizer 🔢¶
A count vectorizer outputs a text as a matrix of counts of the related word.
It has a vocabulary that includes every word that is present in the data.
When it converts a text into a vector, it first counts all the words.
For example, if the first digit of the vector contains the word "hello" and "hello" is counted 2 times in the text, then the number 2 will be in this position.
The advantage of this method is that the vector always has the same size and is therefore independent of the input.
TFidf 📐¶
Here is a very in-depth explanation:
https://medium.com/@cmukesh8688/tf-idf-vectorizer-scikit-learn-dbc0244a911a
Somehow to submit something the output needs to be integers otherwise the evaluation will fail.
import re
tlist = test_dataset.text.tolist()
def stemSentence(sentence):
token_words=word_tokenize(sentence)
token_words
stem_sentence=[]
for word in token_words:
stem_sentence.append(lemmatizer.lemmatize(word))
stem_sentence.append(" ")
return "".join(stem_sentence)
tlist_updated = []
for sent in tlist:
sent = sent.replace('\n', ' ')
# sent = clean(sent)
sent = re.sub("\$.*?\$", "", sent)
sent = re.sub("-", " ", sent)
sent = re.sub(r'[^\w\s]', '', sent)
sent = re.sub("\(", "", sent)
sent = re.sub("\)", "", sent)
sent = re.sub(' +', ' ', sent)
sent = sent.lower()
sent = stemSentence(sent)
tlist_updated.append(sent)
tlist_updated
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
count_vect = CountVectorizer(max_features = 512)
X_train_counts = count_vect.fit_transform(tlist_updated)
tf_transformer = TfidfTransformer(use_idf=True).fit(X_train_counts)
X_train_tf = tf_transformer.transform(X_train_counts)
X_train_tf = np.round(X_train_tf.toarray()*100).astype(int)
test_dataset.feature = [str(i) for i in X_train_tf.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)
!DATASET_PATH=$AICROWD_DATASET_PATH \
aicrowd -v notebook submit \
--assets-dir $AICROWD_ASSETS_DIR \
--challenge nlp-feature-engineering
Congratulations π!
Now you have an understanding of how to do simple feature engineering in NLP.
If you liked it please leave a like.
PS: The original notebook I copied it from is the getting-stated notebook by
Shubhamaicrowd.
Content
Comments
You must login before you can post a comment.