Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions CNN/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# CNN Project

This project implements a Convolutional Neural Network (CNN) using TensorFlow and Keras to classify images from the Fashion MNIST dataset.


## Getting Started

### Prerequisites

Make sure you have Python installed along with required packages listed in `requirements.txt`.

### Installation

```bash
pip install -r requirements.txt
```

## Introduction to CNNs
A Convolutional Neural Network (CNN) is a type of deep learning model primarily used for analyzing visual data. CNNs are particularly effective in tasks such as image classification, object detection, and video analysis due to their ability to automatically detect and learn features from images.


## Key Components of CNNs
1. **Convolutional Layers**:
- Apply filters to input images to extract features such as edges and textures while preserving spatial relationships between pixels.

2. **Activation Functions**:
- Typically, the ReLU (Rectified Linear Unit) function is used to introduce non-linearity into the model.

3. **Pooling Layers**:
- Reduce the dimensionality of feature maps to decrease computational load while retaining essential information. Common types include Max Pooling and Average Pooling.

4. **Fully Connected Layers**:
- Connect every neuron in one layer to every neuron in the next layer, typically used at the end of the network for classification tasks.

## CNN Architecture
A typical CNN structure consists of:
- Input Layer → Convolutional Layer → Activation Layer → Pooling Layer → Fully Connected Layer → Output Layer

### Example Architecture:
```plaintext
Input -> Conv2D -> ReLU -> MaxPooling -> Conv2D -> ReLU -> Flatten -> Dense -> Softmax
68 changes: 68 additions & 0 deletions CNN/learning_cnn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import numpy as np

Check failure on line 1 in CNN/learning_cnn.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (INP001)

CNN/learning_cnn.py:1:1: INP001 File `CNN/learning_cnn.py` is part of an implicit namespace package. Add an `__init__.py`.
import matplotlib.pyplot as plt
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.utils import to_categorical

# Load the Fashion MNIST dataset

Check failure on line 6 in CNN/learning_cnn.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

CNN/learning_cnn.py:1:1: I001 Import block is un-sorted or un-formatted
(train_images, train_labels), (test_images, test_labels) = (
datasets.fashion_mnist.load_data()
)

# Normalize the images to values between 0 and 1
train_images = train_images.astype("float32") / 255.0
test_images = test_images.astype("float32") / 255.0

# Reshape the images to add a channel dimension (for grayscale images)
train_images = np.expand_dims(train_images, axis=-1)
test_images = np.expand_dims(test_images, axis=-1)

# One-hot encode the labels
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

# Define the CNN model
model = models.Sequential(
[
layers.Conv2D(32, (3, 3), activation="relu", input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation="relu"),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation="relu"),
layers.Flatten(),
layers.Dense(64, activation="relu"),
layers.Dense(10, activation="softmax"),
]
)

# Compile the model
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])

# Train the model
history = model.fit(
train_images, train_labels, epochs=10, batch_size=64, validation_split=0.2
)

# Evaluate the model on the test set
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f"Test accuracy: {test_acc:.4f}")

# Plot training & validation accuracy values
plt.plot(history.history["accuracy"], label="Train Accuracy")
plt.plot(history.history["val_accuracy"], label="Validation Accuracy")
plt.title("Model Accuracy")
plt.ylabel("Accuracy")
plt.xlabel("Epoch")
plt.legend()
plt.savefig("outputs/accuracy.png") # Save accuracy plot

# Plot training & validation loss values
plt.figure()
plt.plot(history.history["loss"], label="Train Loss")
plt.plot(history.history["val_loss"], label="Validation Loss")
plt.title("Model Loss")
plt.ylabel("Loss")
plt.xlabel("Epoch")
plt.legend()
plt.savefig("outputs/loss.png") # Save loss plot

plt.show()
3 changes: 3 additions & 0 deletions CNN/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
matplotlib>=3.0.0
numpy>=1.18.0
tensorflow>=2.0.0
1 change: 1 addition & 0 deletions machine_learning/CNN/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Loading