0% found this document useful (0 votes)
98 views5 pages

Artificial Intelligence Mini Project

This project involves building an image classifier using convolutional neural networks to label handwritten digits in the MNIST dataset. The steps include preprocessing the image data, building and training a CNN model, evaluating the model's performance, and making predictions on individual images from the test set. The source code in Python implements these steps using libraries like Keras, TensorFlow, and Scikit-learn.

Uploaded by

Aslam Nizami
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views5 pages

Artificial Intelligence Mini Project

This project involves building an image classifier using convolutional neural networks to label handwritten digits in the MNIST dataset. The steps include preprocessing the image data, building and training a CNN model, evaluating the model's performance, and making predictions on individual images from the test set. The source code in Python implements these steps using libraries like Keras, TensorFlow, and Scikit-learn.

Uploaded by

Aslam Nizami
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Artificial Intelligence Mini

Project

Project Title: Image Classification using Convolutional Neural Networks (CNN)

Project Description: In this mini project, you will learn how to build an image classifier using
Convolutional Neural Networks (CNNs) - a type of neural network commonly used for image
recognition tasks. You will use Python and popular deep-learning libraries like Keras to create a
CNN model that can label handwritten digits correctly.

Steps Involved:

1. Data Preparation: You will need a dataset of labeled images to train and test your
model. In this project, we will use the popular MNIST dataset. You will preprocess the
data by resizing the images, normalizing pixel values, and splitting the data into training
and testing sets.
2. Building the CNN Model: You will build a CNN model using Keras You will define the
architecture of the model, which includes convolutional layers, pooling layers, and fully

Artificial Intelligence Mini Project | 1


connected layers. You will also choose an appropriate loss function and optimizer for
training the model.
3. Training and Testing the Model: You will train the CNN model using the training set
and evaluate its performance on the testing set. You will use techniques like data
augmentation, dropout, and early stopping to improve the model's accuracy.
4. Fine-Tuning the Model: You can fine-tune the model by adjusting its hyperparameters,
experimenting with different architectures, or using transfer learning to leverage pre-
trained models.
5. Deploying the Model: Once you have a trained and optimized CNN model, you can
deploy it to classify new images. You will learn how to build a command-line interface
that accepts an image and returns its predicted class.

Source Code in Python:


—----------------------------------------------------------------------------------------------------------------------------
#Importing Necessary Libraries
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.utils import to_categorical

from sklearn.metrics import classification_report, confusion_matrix, accuracy_score,


precision_score, recall_score

#Importing the MNIST Dataset


from tensorflow.keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print("Shape of X_train : ", X_train.shape)
print("Shape of X_test : ", X_test.shape)
print("Shape of y_train : ", y_train.shape)
print("Shape of y_test : ", y_test.shape)

#Loading Sample Images


plt.figure(figsize=(20,20))

plt.subplot(1,10,1)
plt.imshow(X_train[0])
plt.subplot(1,10,2)
plt.imshow(X_train[1])
plt.subplot(1,10,3)
plt.imshow(X_train[2])
plt.subplot(1,10,4)
plt.imshow(X_train[3])
plt.subplot(1,10,5)

Artificial Intelligence Mini Project | 2


plt.imshow(X_train[4])
plt.subplot(1,10,6)
plt.imshow(X_train[5])
plt.subplot(1,10,7)
plt.imshow(X_train[6])
plt.subplot(1,10,8)
plt.imshow(X_train[7])
plt.subplot(1,10,9)
plt.imshow(X_train[8])
plt.subplot(1,10,10)
plt.imshow(X_train[9])

plt.figure(figsize=(20,20))

plt.subplot(1,10,1)
plt.imshow(X_train[150])
plt.subplot(1,10,2)
plt.imshow(X_train[162])
plt.subplot(1,10,3)
plt.imshow(X_train[178])
plt.subplot(1,10,4)
plt.imshow(X_train[193])
plt.subplot(1,10,5)
plt.imshow(X_train[205])
plt.subplot(1,10,6)
plt.imshow(X_train[3978])
plt.subplot(1,10,7)
plt.imshow(X_train[456])
plt.subplot(1,10,8)
plt.imshow(X_train[7896])
plt.subplot(1,10,9)
plt.imshow(X_train[57])
plt.subplot(1,10,10)
plt.imshow(X_train[31897])

#Data Preprocessing
print("Shape of X_train : ", X_train.shape)
print("Shape of X_test : ", X_test.shape)

X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)


X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)

input_shape = (28,28,1)

print("Shape of X_train : ", X_train.shape)


print("Shape of X_test : ", X_test.shape)

#One-Hot Encoding
y_cat_train = to_categorical(y_train, 10)

Artificial Intelligence Mini Project | 3


y_cat_test = to_categorical(y_test, 10)

y_cat_train[0:11]

#Scaling feature data


X_train = X_train.astype('float32')
X_test = X_test.astype('float32')

X_train /= 255
X_test /= 255

#Model Creation
model = Sequential()

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


model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())

model.add(Dense(256, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(10, activation='softmax'))

model.compile(loss='categorical_crossentropy',optimizer='adam', metrics=['accuracy'])

model.summary()

#Early Stopping
early_stop = EarlyStopping(monitor='val_loss', patience=2)

#Model Training
model.fit(X_train, y_cat_train, epochs=50, callbacks = [early_stop], validation_data=(X_test,
y_cat_test))

print("The model has successfully trained")


model.save('mnist.h5')
print("Saving the model as mnist.h5")

#Model Performance
training_metrics = pd.DataFrame(model.history.history)
training_metrics.head()
training_metrics[['loss','val_loss']].plot()
training_metrics[['accuracy','val_accuracy']].plot()

score = model.evaluate(X_test, y_cat_test, verbose=0)


print('Test loss:', score[0])
print('Test accuracy:', score[1])

Artificial Intelligence Mini Project | 4


#Model Predictions
predictions = np.argmax(model.predict(X_test), axis=-1)
print(classification_report(y_test, predictions))
print(confusion_matrix(y_test, predictions))

#Predicting Individual Images


new_img = X_test[95]
plt.imshow(new_img)
y_test[95]

np.argmax(model.predict(new_img.reshape(1,28,28,1)), axis=-1)
new_img2 = X_test[0]
plt.imshow(new_img2)
Y_test[0]

np.argmax(model.predict(new_img2.reshape(1,28,28,1)), axis=-1)
new_img3 = X_test[397]
plt.imshow(new_img3)

y_test[397]

—----------------------------------------------------------------------------------------------------------------------------

This mini project will give you a hands-on experience with building and training a CNN model for
image classification, one of the most popular applications of artificial intelligence. You can also
extend the project by experimenting with different datasets, architectures, and techniques to
improve the model's performance.

Artificial Intelligence Mini Project | 5

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy