# Getting Started Code for Cervc Educational Challenge¶

## Download Necessary Packages¶

In [ ]:
import sys
!pip install numpy
!pip install pandas
!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 [ ]:
!rm -rf data
!mkdir data
!wget https://s3.eu-central-1.wasabisys.com/aicrowd-practice-challenges/public/cervc/v0.1/test.csv
!wget https://s3.eu-central-1.wasabisys.com/aicrowd-practice-challenges/public/cervc/v0.1/train.csv
!mv train.csv data/train.csv
!mv test.csv data/test.csv


## Import packages¶

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


## 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 [11]:
all_data_path = "data/train.csv" #path where data is stored

In [12]:
all_data = pd.read_csv(all_data_path) #load data in dataframe using pandas


## Visualize the data 👀¶

In [13]:
all_data.head()

Out[13]:
Age Number.of.sexual.partners First.sexual.intercourse Num.of.pregnancies Smokes Smokes..years. Hormonal.Contraceptives Hormonal.Contraceptives..years. IUD IUD..years. STDs STDs..number. STDs..Number.of.diagnosis STDs..Time.since.first.diagnosis STDs..Time.since.last.diagnosis Biopsy
0 36 3 20 2 0 0.000000 1 6.00 0 0.0 1 1 1 16 16 0
1 29 2 20 1 0 0.000000 1 0.50 0 0.0 0 0 0 1 1 0
2 36 3 18 3 1 1.266973 1 9.00 0 0.0 0 0 0 1 1 0
3 20 3 17 2 0 0.000000 1 0.25 0 0.0 0 0 0 1 1 1
4 29 5 17 5 0 0.000000 1 0.58 0 0.0 0 0 0 1 1 0

There are total of 15 attributes out of which first 14 features include demographic data such as age, lifestyle, and medical history. The last attribute called Biopsy is target variable and it's value is 0 for Healthy and 1 for Cancer.

## Split Data into Train and Validation 🔪¶

• The next step is to think of a way to test how well our model is performing. we cannot use the test data given as it does not contain the data labels for us to verify.
• The workaround this is to split the given training data into training and validation. Typically validation sets give us an idea of how our model will perform on unforeseen data. it is like holding back a chunk of data while training our model and then using it to for the purpose of testing. it is a standard way to fine-tune hyperparameters in a model.
• There are multiple ways to split a dataset into validation and training sets. following are two popular ways to go about it, k-fold, leave one out. 🧐
• Validation sets are also used to avoid your model from overfitting on the train dataset.
In [14]:
X_train, X_val= train_test_split(all_data, test_size=0.2, random_state=42)

• We have decided to split the data with 20 % as validation and 80 % as training.
• To learn more about the train_test_split function click here. 🧐
• This is of course the simplest way to validate your model by simply taking a random chunk of the train set and setting it aside solely for the purpose of testing our train model on unseen data. as mentioned in the previous block, you can experiment 🔬 with and choose more sophisticated techniques and make your model better.
• Now, since we have our data splitted into train and validation sets, we need to get the corresponding labels separated from the data.
• with this step we are all set move to the next step with a prepared dataset.
In [15]:
X_train,y_train = X_train.iloc[:,:-1],X_train.iloc[:,-1]
X_val,y_val = X_val.iloc[:,:-1],X_val.iloc[:,-1]


# TRAINING PHASE 🏋️¶

## 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 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 [16]:
classifier = SVC(gamma='auto')

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

• To start you off, We have used a basic Support Vector Machines classifier here.
• But you can tune parameters and increase the performance. To see the list of parameters visit 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.

To read more about other sklearn 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 Model¶

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

Out[17]:
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3, gamma='auto', 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)

# 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 [18]:
y_pred = classifier.predict(X_val)


## 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 and Log Loss are the metrics for this challenge
In [19]:
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')

/home/shubh/.local/lib/python3.5/site-packages/sklearn/metrics/classification.py:1437: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.
'precision', 'predicted', average, warn_for)

In [20]:
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.9492753623188406
Recall of the model is : 0.9492753623188406
Precision of the model is : 0.9492753623188406
F1 score of the model is : 0.48698884758364314


# 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 [21]:
final_test_path = "data/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 [22]:
submission = classifier.predict(final_test)


## Save the prediction to csv¶

In [23]:
submission = pd.DataFrame(submission)
submission.to_csv('submission.csv',header=['Biopsy'],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.

## To download the generated csv in colab run the below command¶

In [1]:
try:
from google.colab import files
files.download('submission.csv')
except:
print("only in Colab")

only in Colab


### Well Done! 👍 We are all set to make a submission and see you name on leaderborad. Let navigate to challenge page and make one.¶

In [ ]: