To open this notebook on Google Computing platform Colab, click below!¶
Download Necessary Packages¶
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 our train and test datasets. We will be training a classifier on the training dataset and make predictions on test dataset.
#Donwload the datasets
!wget https://s3.eu-central-1.wasabisys.com/aicrowd-practice-challenges/public/minileaves/v0.1/train-images.npy
!wget https://s3.eu-central-1.wasabisys.com/aicrowd-practice-challenges/public/minileaves/v0.1/train-labels.npy
!wget https://s3.eu-central-1.wasabisys.com/aicrowd-practice-challenges/public/minileaves/v0.1/test-images.npy
!wget https://s3.eu-central-1.wasabisys.com/aicrowd-practice-challenges/public/minileaves/v0.1/all_classes.txt
Import packages¶
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
import matplotlib.pyplot as plt
Load Data¶
train_images_path = "train-images.npy" #path where data is stored
train_labels_path = "train-labels.npy"
train_images = np.load(train_images_path)
train_labels = np.load(train_labels_path)
# Load Class mapping
class_names = [x.strip() for x in open("all_classes.txt").readlines()]
Visualize the data¶
from mpl_toolkits.axes_grid1 import ImageGrid
def random_data_sample():
"""
Returns a random data sample from the training set
"""
global class_name, train_images, train_labels
random_index = np.random.randint(0, train_images.shape[0])
# Render the image
image_array = train_images[random_index]
class_label = train_labels[random_index] # an integral number in [0-38)
class_name = class_names[class_label] # a human readable class name
return image_array, class_label, class_name
"""
Render a 7x7 grid of 49 randomly sampled images
from the training set
"""
grid_shape = (7, 7)
fig = plt.figure(figsize=(10, 10))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=grid_shape, # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
data_samples = [random_data_sample() for _ in range(grid_shape[0] * grid_shape[1])]
for ax, data_sample in zip(grid, data_samples):
image_array, class_label, class_name = data_sample
ax.imshow(image_array)
ax.axis('off')
plt.savefig("image-grid.png")
Dataset Distribution¶
from collections import Counter
data_counter = Counter(train_labels)
unique_class_indices = data_counter.keys()
for _class_index in unique_class_indices:
print("Class Index : ", _class_index)
print("Class Name : ", class_names[_class_index])
print("Number of images in the dataset : ", data_counter[_class_index])
print("="*100)
# TODO : Add a bar plot of the distribution of the classes here
Split Data into Train and Validation¶
Now we eventually 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 ? We split our dataset into a training set and a validation set. 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 training dataset.
X_train, X_val= train_test_split(train_images, test_size=0.2, random_state=42)
y_train, y_val= train_test_split(train_labels, test_size=0.2, random_state=42)
## Note : Given that we use the same random state in both the splits,
## and both `train_images` and `train_labels` have the same number of (aligned) elements,
## the overall alignment between X_train and the corresponding Y_train will be retained.
Here we have selected the size of the testing 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.
Define the Classifier¶
Now we come to the juicy part. 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.
classifier = MLPClassifier(hidden_layer_sizes=(20, 20))
#from sklearn.linear_model import LogisticRegression
# classifier = LogisticRegression()
## NOTE : This is definitely not the most optimal approach for this problem.
## This code is provided to help you get started quickly, and should be treated
## as suck
We have used a very simple Multi Layer Perceptron 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.
Define data pre-processors¶
"""
Some of the models have different requirements in terms of what form of the data they can consume.
In this example, we will use
a very simple Multi Layer Perceptron (explained further in the notebook),
which expects a single dimensional representation for every data point.
Hence, we will define some pre-processors which can help flatten the data,
and also normalize the data as necessary.
"""
def preprocess_X(X_array):
assert X_array.shape[1:] == (32, 32, 3) # as the images are of the dimension 32x32x3
# We normalize the whole array to a [0-1] range. As the pixel RGB values are uint8 values in the range[0, 256],
# we will normalize simply by dividing the whole array by 255
X_array = X_array.astype(np.float32) / 255.0
# Now, we will reshape the ndarray of shape (N, 32, 32, 3) to (N, 32*32*3), where N is the number of samples
# present in the dataset
X_array = X_array.reshape(X_array.shape[0], 32*32*3)
return X_array
X_train = preprocess_X(X_train)
X_val = preprocess_X(X_val)
Train the classifier¶
classifier.fit(X_train, y_train)
Predict on Validation¶
Now we predict our trained classifier on the validation set and evaluate our model
y_pred = classifier.predict(X_val)
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')
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)
Prediction on Evaluation Set¶
Load Test Set¶
test_file_path = "test-images.npy"
test_images = np.load(test_file_path)
Predict Test Set¶
The moment of truth! Predict on test set and then we can make the submission.
# We first pre-process the test images, the same way we pre-process the train images
test_images = preprocess_X(test_images)
submission = classifier.predict(test_images)
Save the prediction to csv¶
#change the header according to the submission guidelines
import pandas as pd
submission = pd.DataFrame(submission)
submission.to_csv('submission.csv',header=['class_index'],index=False)
Note: Do take a look at the submission format.The submission file should contain a header.
To download the generated csv in colab run the below command¶
# This block is only relevant if you are running this notebook on Google Colab
from google.colab import files
files.download('submission.csv')