0% found this document useful (0 votes)
3 views7 pages

DL3

The document outlines a Python script utilizing TensorFlow and Keras to load and preprocess the Fashion MNIST dataset, consisting of 60,000 training images and 10,000 test images. It details the creation of a neural network model, training it for 5 epochs, and evaluating its accuracy, which reached approximately 88%. Additionally, it includes functions for visualizing predictions and comparing them with true labels.

Uploaded by

sjjs73473
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)
3 views7 pages

DL3

The document outlines a Python script utilizing TensorFlow and Keras to load and preprocess the Fashion MNIST dataset, consisting of 60,000 training images and 10,000 test images. It details the creation of a neural network model, training it for 5 epochs, and evaluating its accuracy, which reached approximately 88%. Additionally, it includes functions for visualizing predictions and comparing them with true labels.

Uploaded by

sjjs73473
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/ 7

15/04/2025, 08:38 DL3

PIYUSH AHIRE 39

In [1]: from __future__ import absolute_import, division, print_function


# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

In [2]: fashion_mnist = keras.datasets.fashion_mnist


(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_da

Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-dataset


s/train-labels-idx1-ubyte.gz
29515/29515 ━━━━━━━━━━━━━━━━━━━━ 0s 2us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-dataset
s/train-images-idx3-ubyte.gz
26421880/26421880 ━━━━━━━━━━━━━━━━━━━━ 21s 1us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-dataset
s/t10k-labels-idx1-ubyte.gz
5148/5148 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-dataset
s/t10k-images-idx3-ubyte.gz
4422102/4422102 ━━━━━━━━━━━━━━━━━━━━ 6s 1us/step

In [3]: class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',


'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

In [4]: train_images.shape

Out[4]: (60000, 28, 28)

In [5]: len(train_labels)

Out[5]: 60000

In [6]: train_labels

Out[6]: array([9, 0, 0, ..., 3, 0, 5], dtype=uint8)

In [7]: test_images.shape

Out[7]: (10000, 28, 28)

In [8]: len(test_labels)

Out[8]: 10000

In [9]: plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

file:///C:/Users/deshm/Downloads/DL3 (2).html 1/7


15/04/2025, 08:38 DL3

In [10]: train_images = train_images / 255.0


test_images = test_images / 255.0

In [11]: plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()

file:///C:/Users/deshm/Downloads/DL3 (2).html 2/7


15/04/2025, 08:38 DL3

In [12]: model = keras.Sequential([


keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])

C:\Users\deshm\anaconda3\Lib\site-packages\keras\src\layers\reshaping\flatten.py:
37: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. Wh
en using Sequential models, prefer using an `Input(shape)` object as the first la
yer in the model instead.
super().__init__(**kwargs)

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

In [14]: model.fit(train_images, train_labels, epochs=5)

file:///C:/Users/deshm/Downloads/DL3 (2).html 3/7


15/04/2025, 08:38 DL3

Epoch 1/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 7s 3ms/step - accuracy: 0.7868 - loss: 0.6169
Epoch 2/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 5s 3ms/step - accuracy: 0.8635 - loss: 0.3778
Epoch 3/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 6s 3ms/step - accuracy: 0.8757 - loss: 0.3431
Epoch 4/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 5s 3ms/step - accuracy: 0.8850 - loss: 0.3124
Epoch 5/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 5s 3ms/step - accuracy: 0.8897 - loss: 0.2928
Out[14]: <keras.src.callbacks.history.History at 0x189591adfd0>

In [15]: test_loss, test_acc = model.evaluate(test_images, test_labels)


print('Test accuracy:', test_acc)

313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 2ms/step - accuracy: 0.8773 - loss: 0.3388


Test accuracy: 0.8783000111579895

In [16]: predictions = model.predict(test_images)

313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 2ms/step

In [17]: predictions[0]

Out[17]: array([8.9694855e-05, 3.8969080e-07, 7.9476223e-07, 2.6765531e-06,


2.6583541e-06, 3.6756277e-02, 4.5844458e-06, 5.0728031e-02,
2.0136039e-03, 9.1040134e-01], dtype=float32)

In [18]: np.argmax(predictions[0])

Out[18]: 9

In [19]: test_labels[0]

Out[19]: 9

In [20]: import numpy as np


import matplotlib.pyplot as plt

def plot_image(i, predictions_array, true_label, img):


predictions_array, true_label, img = predictions_array[i], true_label[i], im
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)

predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'

plt.xlabel(
"{} {:2.0f}% ({})".format(
class_names[predicted_label],
100 * np.max(predictions_array),
class_names[true_label]
),
color=color
)

file:///C:/Users/deshm/Downloads/DL3 (2).html 4/7


15/04/2025, 08:38 DL3

def plot_value_array(i, predictions_array, true_label):


predictions_array, true_label = predictions_array[i], true_label[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')

In [21]: i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
plt.show()

In [22]: i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
plt.show()

file:///C:/Users/deshm/Downloads/DL3 (2).html 5/7


15/04/2025, 08:38 DL3

In [23]: # Plot the first X test images, their predicted label, and the true label
# Color correct predictions in blue, incorrect predictions in red
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions, test_labels)
plt.show()

In [24]: # Grab an image from the test dataset


img = test_images[0]
print(img.shape)

(28, 28)

In [25]: # Add the image to a batch where it's the only member.
img = (np.expand_dims(img,0))
print(img.shape)

(1, 28, 28)

In [26]: predictions_single = model.predict(img)


print(predictions_single)

file:///C:/Users/deshm/Downloads/DL3 (2).html 6/7


15/04/2025, 08:38 DL3

1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 26ms/step


[[8.9694840e-05 3.8969074e-07 7.9476291e-07 2.6765551e-06 2.6583566e-06
3.6756210e-02 4.5844454e-06 5.0728064e-02 2.0136037e-03 9.1040123e-01]]

In [27]: plot_value_array(0, predictions_single, test_labels)


_ = plt.xticks(range(10), class_names, rotation=45)

In [28]: np.argmax(predictions_single[0])

Out[28]: 9

file:///C:/Users/deshm/Downloads/DL3 (2).html 7/7

You might also like