Baseline for INCPR Educational Challenge on AIcrowd¶

Download Necessary Packages¶

In [ ]:
import sys
!{sys.executable} -m pip install numpy
!{sys.executable} -m pip install pandas
!{sys.executable} -m pip install scikit-learn


Download data¶

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

In [ ]:
!wget https://s3.eu-central-1.wasabisys.com/aicrowd-public-datasets/aicrowd_educational_incpr/data/public/test.csv
!wget https://s3.eu-central-1.wasabisys.com/aicrowd-public-datasets/aicrowd_educational_incpr/data/public/train.csv


Import packages¶

In [ ]:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score,precision_score,recall_score,accuracy_score


Load Data¶

We use pandas library to load our data. Pandas loads them into dataframes which helps us analyze our data easily. Learn more about it here

In [ ]:
train_data_path = "train.csv" #path where data is stored

In [ ]:
train_data = pd.read_csv(train_data_path) #load data in dataframe using pandas


Visualize data¶

In [ ]:
train_data.head()


We can see each column contains different attributes. The dataset is a mixture of both data type "int" and "text".

Select the columns which you need to train on. We can also select columns with data type as text, but then we need to map these text to numbers i.e. encode them and then select them. To know more about encoding, visit here.

In [ ]:
train_data = train_data[['age','education num','capital gain','capital loss','working hours per week','income']]


Split Data into Train and Validation¶

Now we want to see how well our classifier is performing, but we dont have the test data labels with us to check. What do we do ? So we split our dataset into train and validation. The idea is that we test our classifier on validation set in order to get an idea of how well our classifier works. This way we can also ensure that we dont overfit on the train dataset. There are many ways to do validation like k-fold,leave one out, etc

In [ ]:
X_train, X_val= train_test_split(train_data, test_size=0.2, random_state=42)


Here we have selected the size of the validation data to be 20% of the total data. You can change it and see what effect it has on the accuracies. To learn more about the train_test_split function click here.

Now, since we have our data splitted into train and validation sets, we need to get the label separated from the data.

Check which column contains the variable that needs to be predicted. Here it is the last column.

In [ ]:
X_train,y_train = X_train.iloc[:,:-1],X_train.iloc[:,-1]
X_val,y_val = X_val.iloc[:,:-1],X_val.iloc[:,-1]


Define the Classifier¶

We have fixed our data and now we train a classifier. The classifier will learn the function by looking at the inputs and corresponding outputs. There are a ton of classifiers to choose from some being Logistic Regression, SVM, Random Forests, Decision Trees, etc.
Tip: A good model doesnt depend solely on the classifier but on the features(columns) you choose. So make sure to play with your data and keep only whats important.

In [106]:
classifier = SVC(gamma='auto')

#from sklearn.linear_model import LogisticRegression
# classifier = LogisticRegression()


We have used Support Vector Machines as a classifier here and set few of the parameteres. But one can set more parameters and increase the performance. To see the list of parameters visit here.

We can also use other classifiers. To read more about sklean classifiers visit here. Try and use other classifiers to see how the performance of your model changes. Try using Logistic Regression or MLP and compare how the performance changes.

Train the classifier¶

In [107]:
classifier.fit(X_train, y_train)

/home/ayush/.local/lib/python3.7/site-packages/sklearn/svm/base.py:193: FutureWarning: The default value of gamma will change from 'auto' to 'scale' in version 0.22 to account better for unscaled features. Set gamma explicitly to 'auto' or 'scale' to avoid this warning.
"avoid this warning.", FutureWarning)

Out[107]:
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3, gamma='auto_deprecated',
kernel='rbf', max_iter=-1, probability=False, random_state=None,
shrinking=True, tol=0.001, verbose=False)

Got a warning! Dont worry, its just beacuse the number of iteration is very less(defined in the classifier in the above cell).Increase the number of iterations and see if the warning vanishes and also see how the performance changes.Do remember increasing iterations also increases the running time.( Hint: max_iter=500)

Predict on Validation¶

Now we predict our trained classifier on the validation set and evaluate our model

In [6]:
y_pred = classifier.predict(X_val)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-3b59f90ea64e> in <module>
----> 1 y_pred = classifier.predict(X_val)

NameError: name 'classifier' is not defined

Evaluate the Performance¶

We use the same metrics as that will be used for the test set.
F1 score and Log Loss are the metrics for this challenge

In [115]:
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 [116]:
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.89356210142727
Recall of the model is : 0.89356210142727
Precision of the model is : 0.89356210142727
F1 score of the model is : 0.6058161925441079


Prediction on Evaluation Set¶

Load Test Set¶

Load the test data now

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


Predict Test Set¶

Time for the moment of truth! Predict on test set and time to make the submission.

In [118]:
submission = classifier.predict(final_test)


Save the prediction to csv¶

In [ ]:
submission = pd.DataFrame(submission)
submission.to_csv('/tmp/submission.csv',header=['income'],index=False)


Note: Do take a look at the submission format.The submission file should contain a header.For eg here it is "income".

To download the generated csv in collab run the below command¶

In [ ]:
from google.colab import files
files.download('/tmp/submission.csv')


1 Like