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

Dllab4

The document loads and prepares fashion MNIST data, builds and trains a neural network model to classify the images, then tests the model and visualizes the results.
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)
8 views7 pages

Dllab4

The document loads and prepares fashion MNIST data, builds and trains a neural network model to classify the images, then tests the model and visualizes the results.
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

210006930 JOHN JOSHUA

# Step 1: Load libraries


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn
import tensorflow as tf
import keras
import keras.layers as layers
from keras.models import Sequential
from keras.callbacks import TensorBoard
from sklearn.model_selection import train_test_split
from keras.layers import Dense
from tensorflow.keras.utils import to_categorical

# Step 2: Load data (Fashion MNIST)


(x_train, y_train), (x_test, y_test) =
keras.datasets.fashion_mnist.load_data()
train_images = x_train
train_labels = y_train
print(train_images.shape) # (60000, 28, 28)
print(train_labels.shape) # (60000,)
test_images = x_test
test_labels = y_test

print(test_images.shape)

train_images = (train_images / 255) - 0.5


test_images = (test_images / 255) - 0.5
# Flatten the images.
train_images = train_images.reshape((-1, 784))
test_images = test_images.reshape((-1, 784))
print(train_images.shape) # (60000, 784)
print(test_images.shape) # (10000, 784)

# Step 4: Build the model.


model = Sequential([Dense(64, activation='relu', input_shape=(784,)),
Dense(64, activation='relu'),
Dense(10, activation='softmax'),
])
print(model.summary())

# Step 5: Compile model


model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy', # Use
'sparse_categorical_crossentropy' for Fashion MNIST
metrics=['accuracy'],
)

# Step 6: Train the model


hist = model.fit(
train_images,
train_labels,
epochs=5,
validation_split=0.2,
batch_size=32
)

# Step 7: Testing the Model


model.evaluate(test_images, test_labels)

# Predict on the first 5 test images.


predictions = model.predict(test_images[:5])

# Print our model's predictions.


print(np.argmax(predictions, axis=1)) # [7, 2, 1, 0, 4]

# Check our predictions against the ground truths.


print(test_images[:1].shape)

first_image = test_images[:1]
first_image = np.array(first_image, dtype='float')
pixels = first_image.reshape((28, 28))
plt.imshow(pixels, cmap='gray')
plt.show()

# Step 8: Plot the first 25 images from the training set with class
names
# Map class labels to corresponding digit names
class_names = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
"Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]

# Function to plot images with class names


def plot_images(images, labels, class_names, title):
plt.figure(figsize=(10, 5))
for i in range(min(len(images), 25)):
plt.subplot(5, 5, i + 1)
plt.imshow(images[i].reshape(28, 28), cmap='gray')
plt.title(class_names[labels[i]])
plt.axis('off')
plt.suptitle(title)
plt.show()

# Plot the first 25 images from the training set


plot_images(train_images[:25], train_labels[:25], class_names, 'First
25 Images from Training Set')
# Step 9: Visualizing losses and accuracy

# Plot accuracy
plt.figure()
plt.plot(hist.history["accuracy"], label="Train Accuracy",
color="black")
plt.plot(hist.history["val_accuracy"], label="Validation Accuracy",
color="red", linestyle="dashed")
plt.title("Model Accuracy", color="darkred")
plt.xlabel("Train Accuracy")
plt.ylabel("Validation Accuracy")
plt.legend()
plt.show()

# Plot loss
plt.figure()
plt.plot(hist.history["loss"], label="Train Loss", color="black")
plt.plot(hist.history["val_loss"], label="Validation Loss",
color="red", linestyle="dashed")
plt.title("Model Loss", color="darkred")
plt.xlabel("Train Loss")
plt.ylabel("Validation Loss")
plt.legend()
plt.show()

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


keras-datasets/train-labels-idx1-ubyte.gz
29515/29515 [==============================] - 0s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-
keras-datasets/train-images-idx3-ubyte.gz
26421880/26421880 [==============================] - 0s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-
keras-datasets/t10k-labels-idx1-ubyte.gz
5148/5148 [==============================] - 0s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-
keras-datasets/t10k-images-idx3-ubyte.gz
4422102/4422102 [==============================] - 0s 0us/step
(60000, 28, 28)
(60000,)
(10000, 28, 28)
(60000, 784)
(10000, 784)
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 64) 50240

dense_1 (Dense) (None, 64) 4160


dense_2 (Dense) (None, 10) 650

=================================================================
Total params: 55050 (215.04 KB)
Trainable params: 55050 (215.04 KB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________
None
Epoch 1/5
1500/1500 [==============================] - 11s 6ms/step - loss:
0.5264 - accuracy: 0.8081 - val_loss: 0.4406 - val_accuracy: 0.8400
Epoch 2/5
1500/1500 [==============================] - 12s 8ms/step - loss:
0.3934 - accuracy: 0.8555 - val_loss: 0.4127 - val_accuracy: 0.8480
Epoch 3/5
1500/1500 [==============================] - 13s 9ms/step - loss:
0.3539 - accuracy: 0.8703 - val_loss: 0.3666 - val_accuracy: 0.8658
Epoch 4/5
1500/1500 [==============================] - 5s 3ms/step - loss:
0.3294 - accuracy: 0.8780 - val_loss: 0.3606 - val_accuracy: 0.8710
Epoch 5/5
1500/1500 [==============================] - 6s 4ms/step - loss:
0.3094 - accuracy: 0.8844 - val_loss: 0.3467 - val_accuracy: 0.8748
313/313 [==============================] - 1s 2ms/step - loss: 0.3758
- accuracy: 0.8671
1/1 [==============================] - 0s 102ms/step
[9 2 1 1 6]
(1, 784)

You might also like