diff --git a/CNN/README.md b/CNN/README.md new file mode 100644 index 000000000000..9d9c4036d415 --- /dev/null +++ b/CNN/README.md @@ -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 diff --git a/CNN/learning_cnn.py b/CNN/learning_cnn.py new file mode 100644 index 000000000000..b64f1184b8ce --- /dev/null +++ b/CNN/learning_cnn.py @@ -0,0 +1,68 @@ +import numpy as np +import matplotlib.pyplot as plt +from tensorflow.keras import datasets, layers, models +from tensorflow.keras.utils import to_categorical + +# Load the Fashion MNIST dataset +(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() diff --git a/CNN/requirements.txt b/CNN/requirements.txt new file mode 100644 index 000000000000..5310a12b34b7 --- /dev/null +++ b/CNN/requirements.txt @@ -0,0 +1,3 @@ +matplotlib>=3.0.0 +numpy>=1.18.0 +tensorflow>=2.0.0 diff --git a/machine_learning/CNN/README.md b/machine_learning/CNN/README.md new file mode 100644 index 000000000000..8b137891791f --- /dev/null +++ b/machine_learning/CNN/README.md @@ -0,0 +1 @@ +