Galaxy images classification — Convolutional Neural Network (CNN) explained with codes
By: Jonathan C.T. Kuo
Tags: Image Classification, Programming, Convolutional Network, TensorFlow, Machine Learning

This is a multiclass image classification problem that uses convolutional neural network with TensorFlow (Keras api) to train on the Galaxy10 dataset.

First let’s download the dataset. In this tutorial, I’m running the code in Google Colab.

!pip install astroNN

Next we import the libraries.

from astroNN.datasets import galaxy10

from astroNN.datasets.galaxy10 import galaxy10cls_lookup import keras

from keras.models import Sequential

from keras.layers import Dense, Dropout, Flatten

from keras.layers import Conv2D, MaxPooling2D

from keras.utils import to_categorical

from keras.preprocessing import image import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import matplotlib.image as mpimg

from sklearn.model_selection import train_test_split

from tqdm import tqdm

Now, we can load the data and preprocess them. Each image has a corresponding label from 0 to 9. In order to make the computation more effectively later, we can one-hot encode each label with the to_categorical() function. In addition, we normalize the image values between 0 and 1 as a good practice to speed up the computational time.

images, labels = galaxy10.load_data() labels = labels.astype(np.float32)

labels = to_categorical(labels)

images = images.astype(np.float32)

images = images/255

Here we can take a look at some images with their corresponding labels from the training .

def show_image(image_data,label):

label = galaxy10cls_lookup(int(label))

plt.imshow(image_data)

plt.title(label)

plt.show() for i in range(3):

show_image(images[i], i)

Next we separate the training set and the test set with the train_test_split() function from sklearn.

X_train, X_test, y_train, y_test = train_test_split(images, labels, test_size = 0.15) print(X_train.shape)

print(y_train.shape)

(18517, 69, 69, 3)

(18517, 10)

Now we also know the shape of the training set. There are 18517 images with 69 by 69 pixels with 3 (RGB) channels. The shape of the test set should be the same as the training set.

CNN model

The first layer is a convolutional layer with 32 output nodes. We also apply a 3 by 3 filter and a Rectified Linear Unit activation function in it and the input shape. Notice that the MaxPooling layer and the Dropout layer could help prevent the network from overfitting.

Finally we flatten the output data to a shape of 1D so that in the last Dense layer the model could make a choice between 0 and 9 to determine which label an image should belong to.

model = Sequential() model.add(Conv2D(32, kernel_size=(3,3),activation='relu',

input_shape=(69,69,3))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.summary()

Compile and Train the model

model.compile(

loss='categorical_crossentropy',

optimizer='Adam',

metrics=['accuracy']) model.fit(X_train, y_train, epochs=20,

validation_data=(X_test, y_test))

Result

Training and Validation loss

plt.plot(model.history.history['loss'],color='b',

label='Training Loss') plt.plot(model.history.history['val_loss'],color='r',

label='Validation Loss') plt.legend()

plt.show()

Training and Testing accuracy

plt.plot(model.history.history['accuracy'],color='b',

label='Training Accuracy') plt.plot(model.history.history['val_accuracy'],color='r',

label='Validation Accuracy') plt.legend()

plt.show()

Conclusion

From the accuracy plot we can see that the model might be overfitting since the training accuracy keeps going up linearly while the validation accuracy plateau at an early stage. However the model still has a nearly 75 % accuracy in classifying the images which is far greater than the result of random guessing (10%).