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)
GO ONE LEVEL DEEPER
What the CNN pipeline is doing
The code is easier to debug when each tensor transformation has a clear purpose, from the 28×28 image through the final ten-class prediction.
Prepare
Reshape to 28×28×1 and scale pixel values to 0–1.
Extract
Convolution and pooling layers learn increasingly useful visual patterns.
Classify
Dense output units convert learned features into class probabilities.
Keep in mind
- Confirm the output shape matches the label encoding.
- Use validation data for model choices and reserve the test set for the final estimate.
- Review a confusion matrix to see which clothing classes the model confuses.