import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
import random
random.seed(1)
np.random.seed(1)
tf.random.set_seed(1)
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()
# checking unique labels
np.unique(y_train)
# reshaping to one channel color
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
# normalizing
X_train_normalized = X_train.astype('float32')/255.0
X_test_normalized = X_test.astype('float32')/255.0
#encoding label classes
y_train_encoded = tf.keras.utils.to_categorical(y_train)
y_test_encoded = tf.keras.utils.to_categorical(y_test)
#building CNN model
model = Sequential(
[
Conv2D(64, kernel_size=(3,3), input_shape=(28, 28, 1), activation='relu', padding='same'),
MaxPooling2D(pool_size=(2, 2), padding='same'),
Flatten(),
Dense(100, activation='relu'),
Dense(10, activation='softmax')
]
)
# checking trainable parameters
model.summary()
#compiling model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# fitting with 5 epochs
model.fit(X_train_normalized, y_train_encoded, epochs=5)
# checking training set accuracy
model.evaluate(X_train_normalized, y_train_encoded)
# checking test set accuracy
model.evaluate(X_test_normalized, y_test_encoded)