Deep Learning Project – Image Classification of Fashion Items using ANN
Machine Learning courses with 100+ Real-time projects Start Now!!
Program 1
Classifying Clothing Images Using Artificial Neural Network (ANN)
We want create a model which teach a machine to look at a small grayscale image of a fashion item (like a T-shirt or sneaker) and guess what it is.
# Built-in dataset in Keras (no need to download separately).
# Each image is 28 × 28 pixels (black & white).
# Each image shows one clothing item.
# There are 10 categories (T-shirt/top, trouser, dress, etc.)
# 1. Import libraries
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import fashion_mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.utils import to_categorical
from sklearn.metrics import classification_report, confusion_matrix
import seaborn as sns
# 2. Load Fashion MNIST data
# X_train: 60,000 training images
# y_train: their correct labels
# X_test: 10,000 test images
# y_test: their labels
(X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()
# 3. Normalize pixel values (0 to 1)
# Each pixel value is between 0 and 255.
# We scale them to 0–1 range, which makes training easier.
X_train = X_train / 255.0
X_test = X_test / 255.0
# 4. Convert labels to one-hot vectors
# Instead of labels like 5 or 9, we convert them to vectors like:
# Label 3 → [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
# This is needed for multi-class classification.
y_train_cat = to_categorical(y_train, num_classes=10)
y_test_cat = to_categorical(y_test, num_classes=10)
# 5. Build ANN model
# Flatten: Converts 28×28 image into a long row (784 pixels).
# Dense(128): First layer with 128 neurons → learns patterns.
# Dense(64): Second layer with 64 neurons → deeper learning.
# Dense(10): Output layer with 10 neurons (for 10 classes).
# softmax helps pick the best class.
model = Sequential([
Flatten(input_shape=(28, 28)), # Converts 28x28 image to 784 vector
Dense(128, activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax') # 10 categories = 10 output neurons
])
# 6. Compile model
# Adam: Optimizer that adjusts the model weights.
# Loss: We want to minimize this during training.
# Accuracy: Our performance metric.
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 7. Train model
# Trains the model using training data.
# 10 epochs: Train the full data 10 times.
# batch_size=128: Use 128 images at a time.
# validation_split=0.1: Keep 10% of training data for validation.
history = model.fit(X_train, y_train_cat, epochs=10, batch_size=128, validation_split=0.1)
# 8. Evaluate model
# We now test how well our model performs on unseen data
loss, acc = model.evaluate(X_test, y_test_cat)
print(f"\nTest Accuracy: {acc*100:.2f}%")
# 9. Predict on test set
# Predict the class probabilities for each image.
# Convert probabilities to actual class label (e.g., 0–9).
y_pred_probs = model.predict(X_test)
y_pred = np.argmax(y_pred_probs, axis=1)
y_pred
# 10. Classification Report
# Precision,Recall,F1-score----> for each of the 10 clothing classes.
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
# 11. Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(8,6))
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues")
plt.title("Confusion Matrix")
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.show()
# 12. Display 10 sample predictions
class_names = ['T-shirt', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
plt.figure(figsize=(12,4))
for i in range(10):
plt.subplot(2, 5, i+1)
plt.imshow(X_test[i], cmap='gray')
plt.title(f"Actual: {class_names[y_test[i]]}\nPred: {class_names[y_pred[i]]}")
plt.axis('off')
plt.tight_layout()
plt.show()
Did you like this article? If Yes, please give DataFlair 5 Stars on Google

