0% found this document useful (0 votes)
21 views

Untitled 3

The document loads and preprocesses the MNIST dataset for a convolutional neural network model. It builds a CNN model using Keras with convolutional and dense layers, trains it on the MNIST train set for 5 epochs, and evaluates it on the test set, achieving over 98% accuracy. It then loads a saved model version to make a prediction on a test image.

Uploaded by

Kagade Ajinkya
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)
21 views

Untitled 3

The document loads and preprocesses the MNIST dataset for a convolutional neural network model. It builds a CNN model using Keras with convolutional and dense layers, trains it on the MNIST train set for 5 epochs, and evaluates it on the test set, achieving over 98% accuracy. It then loads a saved model version to make a prediction on a test image.

Uploaded by

Kagade Ajinkya
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/ 4

In 

[2]: from numpy import mean


from numpy import std
from matplotlib import pyplot as plt
from sklearn.model_selection import KFold
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Flatten
from tensorflow.keras.utils import to_categorical
import tensorflow as tf
from tensorflow.keras import models, layers
import numpy as np

In [3]: (X_train,y_train),(X_test,y_test)=mnist.load_data()

In [4]: print('Train: X=%s, y=%s' %(X_train.shape,y_train.shape))


print('Test: X=%s, y=%s' %(X_test.shape,y_test.shape))

Train: X=(60000, 28, 28), y=(60000,)


Test: X=(10000, 28, 28), y=(10000,)

In [5]: for i in range(9):


plt.subplot(3,3,i+1)
plt.imshow(X_train[i],cmap=plt.get_cmap('gray'))
plt.title(y_train[i])
plt.show()

In [6]: X_train=X_train.reshape(X_train.shape[0],28,28,1).astype('float32')
X_test=X_test.reshape(X_test.shape[0],28,28,1).astype('float32')

In [7]: X_train = X_train/255.0


X_test = X_test/255.0

In [8]: y_train = to_categorical(y_train)


y_test = to_categorical(y_test)

In [9]: model=Sequential()
model.add(Conv2D(32,(3,3),activation='relu',kernel_initializer='he_uniform', input_shape
model.add(MaxPooling2D((2,2)))
model.add(Flatten())
model.add(Dense(100,activation='relu',kernel_initializer='he_uniform'))
Loading [MathJax]/extensions/Safe.js
model.add(Dense(10,activation='softmax'))

In [10]: model.summary()

Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 26, 26, 32) 320

max_pooling2d (MaxPooling2D (None, 13, 13, 32) 0


)

flatten (Flatten) (None, 5408) 0

dense (Dense) (None, 100) 540900

dense_1 (Dense) (None, 10) 1010

=================================================================
Total params: 542,230
Trainable params: 542,230
Non-trainable params: 0
_________________________________________________________________

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

In [12]: model.fit(X_train,y_train, epochs=5,validation_data=(X_test,y_test))

Epoch 1/5
1875/1875 [==============================] - 59s 30ms/step - loss: 0.1522 - accuracy: 0.
9535 - val_loss: 0.0652 - val_accuracy: 0.9792
Epoch 2/5
1875/1875 [==============================] - 55s 29ms/step - loss: 0.0514 - accuracy: 0.
9842 - val_loss: 0.0470 - val_accuracy: 0.9851
Epoch 3/5
1875/1875 [==============================] - 57s 30ms/step - loss: 0.0327 - accuracy: 0.
9899 - val_loss: 0.0514 - val_accuracy: 0.9832
Epoch 4/5
1875/1875 [==============================] - 55s 29ms/step - loss: 0.0200 - accuracy: 0.
9935 - val_loss: 0.0536 - val_accuracy: 0.9833
Epoch 5/5
1875/1875 [==============================] - 53s 28ms/step - loss: 0.0138 - accuracy: 0.
9955 - val_loss: 0.0478 - val_accuracy: 0.9854
<keras.callbacks.History at 0x28d3ff52ce0>
Out[12]:

In [13]: test_loss,test_acc=model.evaluate(X_test,y_test)

313/313 [==============================] - 3s 9ms/step - loss: 0.0478 - accuracy: 0.9854

In [14]: print("Test Loss on 10,000 test samples", test_loss)


print("Test Accuracy on 10,000 test samples", test_acc)

Test Loss on 10,000 test samples 0.04779962822794914


Test Accuracy on 10,000 test samples 0.9854000210762024

In [15]: prediction = model.predict([X_test])


print(prediction)
Loading [MathJax]/extensions/Safe.js
plt.imshow(X_test[0])
print(np.argmax(prediction[0]))

313/313 [==============================] - 3s 9ms/step


[[1.10983606e-07 3.99667890e-08 4.72194046e-07 ... 9.99998331e-01
6.96063263e-10 5.76089505e-08]
[5.58988585e-11 1.55616480e-08 1.00000000e+00 ... 1.01407024e-17
2.23336800e-11 1.39545705e-14]
[4.98322361e-09 9.99817431e-01 1.30358785e-07 ... 1.06588448e-06
1.59819717e-06 3.23972472e-07]
...
[3.96185685e-15 1.04309850e-09 1.73739654e-14 ... 2.55249315e-08
4.60337795e-08 1.13966587e-08]
[2.99124198e-10 5.57548712e-12 5.60083013e-13 ... 3.62828084e-12
5.62149580e-06 5.73152394e-11]
[6.47298082e-09 2.73861572e-10 2.35687823e-11 ... 1.22322543e-17
5.84078341e-09 1.85352324e-11]]
7

In [16]: model_version=1
model.save(f'D:/deep-learning-project/saved-model1/{model_version}')

WARNING:absl:Found untraced functions such as _jit_compiled_convolution_op, _update_step


_xla while saving (showing 2 of 2). These functions will not be directly callable after
loading.
INFO:tensorflow:Assets written to: D:/deep-learning-project/saved-model1/1\assets
INFO:tensorflow:Assets written to: D:/deep-learning-project/saved-model1/1\assets

In [17]: import os
model_version = max([int(i) for i in os.listdir('D:/deep-learning-project/saved-model1')
model.save(f"Model/{model_version}")

WARNING:absl:Found untraced functions such as _jit_compiled_convolution_op, _update_step


_xla while saving (showing 2 of 2). These functions will not be directly callable after
loading.
INFO:tensorflow:Assets written to: Model/2\assets
INFO:tensorflow:Assets written to: Model/2\assets

In [20]: image= X_test[6].reshape(-1,28, 28, 1)


prediction = model.predict(image)
print('Predicted Number:',np.argmax(prediction[0]))
plt.imshow(X_test[6])

1/1 [==============================] - 0s 57ms/step


Predicted Number: 4
<matplotlib.image.AxesImage at 0x28d419f8fa0>
Out[20]:

Loading [MathJax]/extensions/Safe.js
In [ ]:

Loading [MathJax]/extensions/Safe.js

You might also like