Baseline for TIRING TEXT Challenge

A getting started code for the TIRING TEXT challenge.


Getting Started Code for Tiring Text Challenge

Authors :

๐Ÿ‘พShrey Gupta

๐Ÿš€Gurkirat Singh

Download Necessary Packages

In [1]:
import sys
!pip install numpy
!pip install pandas
!pip install scikit-learn

!pip install git+https://gitlab.aicrowd.com/aicrowd/aicrowd-cli.git >/dev/null
%load_ext aicrowd.magic
Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (1.19.5)
Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (1.1.5)
Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas) (2018.9)
Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas) (2.8.1)
Requirement already satisfied: numpy>=1.15.4 in /usr/local/lib/python3.7/dist-packages (from pandas) (1.19.5)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)
Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (0.22.2.post1)
Requirement already satisfied: numpy>=1.11.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn) (1.19.5)
Requirement already satisfied: scipy>=0.17.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn) (1.4.1)
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn) (1.0.1)
  Running command git clone -q https://gitlab.aicrowd.com/aicrowd/aicrowd-cli.git /tmp/pip-req-build-wwtu9zs6

Download data

The first step is to download out training and testing dataset. We will be training a classifier on the training data and make predictions testing data. We submit our predictions

In [4]:
API_KEY = "" # Please enter your API Key [https://www.aicrowd.com/participants/me]
%aicrowd login --api-key $API_KEY
API Key valid
Saved API Key successfully!
In [6]:
%aicrowd dataset list -c tiring-text
%aicrowd dataset download -c tiring-text -j 3
              Datasets for challenge #748                                       
โ”‚ # โ”‚ Title                 โ”‚ Description โ”‚      Size โ”‚                         
โ”‚ 0 โ”‚ sample_submission.csv โ”‚ -           โ”‚ 136.43 KB โ”‚                         
โ”‚ 1 โ”‚ test.csv              โ”‚ -           โ”‚  10.10 MB โ”‚                         
โ”‚ 2 โ”‚ train.csv             โ”‚ -           โ”‚  40.85 MB โ”‚                         

Import packages

In [7]:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier 
from sklearn.metrics import f1_score,precision_score,recall_score,accuracy_score,log_loss

Load Data

  • We use pandas ๐Ÿผ library to load our data.
  • Pandas loads the data into dataframes and facilitates us to analyse the data.
  • Learn more about it here ๐Ÿค“
In [8]:
train_data = pd.read_csv("train.csv")

Visualize the data 👀

In [9]:
text tag
1 want this pawn like not even to exist because ... chess
2 ? If I was n't already at that URL , where mig... programming
3 a power is 3x squared the derivative of positi... math
4 Knight to f2 check and the White King has no m... chess
In [10]:
(79376, 2)

The dataset contains texts along with the labels as unscrambled or scrambled.

In [11]:
X,y = train_data['text'],train_data['tag']
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)



Text files are actually series of words (ordered). In order to run machine learning algorithms we need to convert the text files into numerical feature vectors. We will be using bag of words model for our example. Briefly, we segment each text file into words (for English splitting by space), and count number of times each word occurs in each document and finally assign each word an integer id. Each unique word in our dictionary will correspond to a feature (descriptive feature).

Scikit-learn has a high level component which will create feature vectors for us CountVectorizer. More about it here.

In [12]:
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(X_train)
(63500, 86505)

Here by doing count_vect.fit_transform(X_train), we are learning the vocabulary dictionary and it returns a Document-Term matrix. [n_samples, n_features].

TF: Just counting the number of words in each document has 1 issue: it will give more weightage to longer documents than shorter documents. To avoid this, we can use frequency (TF - Term Frequencies) i.e. #count(word) / #Total words, in each document.

TF-IDF: Finally, we can even reduce the weightage of more common words like (the, is, an etc.) which occurs in all document. This is called as TF-IDF i.e Term Frequency times inverse document frequency.

In [13]:
tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
(63500, 86505)

Define the Model

  • We have fixed our data and now we are ready to train our model.

  • There are a ton of classifiers to choose from some being Naive Bayes, Logistic Regression, SVM, Random Forests, Decision Trees, etc.๐Ÿง

  • Remember that there are no hard-laid rules here. you can mix and match classifiers, it is advisable to read up on the numerous techniques and choose the best fit for your solution , experimentation is the key.

  • A good model does not depend solely on the classifier but also on the features you choose. So make sure to analyse and understand your data well and move forward with a clear view of the problem at hand. you can gain important insight from here.๐Ÿง

In [14]:
classifier = DecisionTreeClassifier(max_depth = 2)
  • To start you off, We have used a basic Decision Tree classifier here.
  • Do keep in mind there exist sophisticated techniques for everything, the key as quoted earlier is to search them and experiment to fit your implementation.

Train the Model

Building a pipeline: We can write less code and do all of the above, by building a pipeline as follows:

In [15]:
text_clf = Pipeline([('vect', CountVectorizer(stop_words='english')),
                      ('tfidf', TfidfTransformer()),
                      ('clf', classifier)])
text_clf = text_clf.fit(X_train, y_train)

Tip: To Improve your accuracy you can do something called stemming. Stemming is the process of reducing inflected (or sometimes derived) words to their word stem, base or root form. E.g. A stemming algorithm reduces the words โ€œfishingโ€, โ€œfishedโ€, and โ€œfisherโ€ to the root word, โ€œfishโ€.

You can use NLTK which can be installed from here. NLTK comes with various stemmers which can help reducing the words to their root form.

Validation Phase 🤔

Wonder how well your model learned! Lets check it.

Predict on Validation

Now we predict using our trained model on the validation set we created and evaluate our model on unforeseen data.

In [16]:
y_pred = text_clf.predict(X_val)
['news' 'news' 'news' ... 'fitness' 'news' 'news']

Evaluate the Performance

  • We have used basic metrics to quantify the performance of our model.
  • This is a crucial step, you should reason out the metrics and take hints to improve aspects of your model.
  • Do read up on the meaning and use of different metrics. there exist more metrics and measures, you should learn to use them correctly with respect to the solution,dataset and other factors.
  • F1 score is the metric for this challenge
In [17]:
precision = precision_score(y_val,y_pred,average='micro')
recall = recall_score(y_val,y_pred,average='micro')
accuracy = accuracy_score(y_val,y_pred)
f1 = f1_score(y_val,y_pred,average='macro')
In [18]:
print("Accuracy of the model is :" ,accuracy)
print("Recall of the model is :" ,recall)
print("Precision of the model is :" ,precision)
print("F1 score of the model is :" ,f1)
Accuracy of the model is : 0.3412698412698413
Recall of the model is : 0.3412698412698413
Precision of the model is : 0.3412698412698413
F1 score of the model is : 0.1975052676770655

Testing Phase 😅

We are almost done. We trained and validated on the training data. Now its the time to predict on test set and make a submission.

Load Test Set

Load the test data on which final submission is to be made.

In [19]:
final_test_path = "test.csv"
final_test = pd.read_csv(final_test_path)

Predict Test Set

Predict on the test set and you are all set to make the submission !

In [20]:
submission = text_clf.predict(final_test['text'])

Save the prediction to csv

In [21]:
submission = pd.DataFrame(submission)
submission.to_csv('submission.csv',header=['tag'], index=False)

๐Ÿšง Note :

  • Do take a look at the submission format.
  • The submission file should contain a header.
  • Follow all submission guidelines strictly to avoid inconvenience.
In [22]:
%aicrowd submission create -c tiring-text -f submission.csv # submit the csv
                                       โ”‚ Successfully submitted! โ”‚                                       
                                             Important links                                             
โ”‚  This submission โ”‚ https://www.aicrowd.com/challenges/ml-battleground/submissions/123259              โ”‚
โ”‚                  โ”‚                                                                                    โ”‚
โ”‚  All submissions โ”‚ https://www.aicrowd.com/challenges/ml-battleground/submissions?my_submissions=true โ”‚
โ”‚                  โ”‚                                                                                    โ”‚
โ”‚      Leaderboard โ”‚ https://www.aicrowd.com/challenges/ml-battleground/leaderboards                    โ”‚
โ”‚                  โ”‚                                                                                    โ”‚
โ”‚ Discussion forum โ”‚ https://discourse.aicrowd.com/c/ml-battleground                                    โ”‚
โ”‚                  โ”‚                                                                                    โ”‚
โ”‚   Challenge page โ”‚ https://www.aicrowd.com/challenges/ml-battleground                                 โ”‚
{'submission_id': 123259, 'created_at': '2021-02-25T11:52:30.882Z'}


You must login before you can post a comment.