CNN-FS

๐Ÿง  CNN from Scratch

This project is a simple Convolutional Neural Network (CNN) implemented entirely from scratch using only low-level libraries like NumPy, PIL, and SciPyโ€” no deep learning frameworks (e.g., TensorFlow or PyTorch) are used. It includes image preprocessing, convolution and pooling operations, ReLU and softmax activations, forward/backward propagation, and a fully connected classifier.

CNN Architecture

๐Ÿ“ฆ Releases

Version Stable Test a trained model
0.1.0
โœ…

๐Ÿš€ Features


๐Ÿ–ผ Dataset Structure

Make sure your dataset folder is structured like this:

data/
โ”œโ”€โ”€ class1/
โ”‚   โ”œโ”€โ”€ image1.png
โ”‚   โ”œโ”€โ”€ image2.png
โ”œโ”€โ”€ class2/
โ”‚   โ”œโ”€โ”€ image1.png
โ”‚   โ”œโ”€โ”€ image2.png
โ”œโ”€โ”€ class../
โ”‚   โ”œโ”€โ”€ ..
..

Each subfolder represents a class (e.g., cat, dog), and contains sample images.

To help you get started, weโ€™ve included a starter data folder with example class directories.

๐Ÿงช How It Works

  1. Image Preprocessing:

    • Each image is resized to a fixed size and normalized.
    • Filters (e.g., sharpening, edge detection) are applied using 2D convolution.
    • ReLU activation and 2ร—2 max-pooling reduce spatial dimensions.
  2. Feature Vector:

    • Flattened pooled feature maps are fed into fully connected layers.
  3. Feedforward + Softmax:

    • Dense layers compute activations followed by a softmax for classification.
  4. Backpropagation:

    • Gradients are computed layer-by-layer.
    • Weights and biases are updated using basic gradient descent.

๐Ÿ›  Setup

pip install git+https://github.com/77AXEL/CNN-FS.git

โœ… Training

from cnnfs.model import CNN

model = CNN()
model.init(
    image_size=64,
    batch_size=32,
    h1=128,
    h2=64,
    learning_rate=0.001,
    epochs=400,
    dataset_path="data",
    max_image=200,
    filters=[
        [[0, -1, 0], [-1, 5, -1], [0, -1, 0]],
        [[1, 0, -1], [1, 0, -1], [1, 0, -1]],
        [[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]
    ]
)
model.load_dataset()
model.train_model()
model.save_model()

๐Ÿ” Predicting New Images

model.load_model("model.bin")
prediction = model.predict("test_images/mycat.png")
print("Predicted class:", prediction)

๐Ÿ’ก Example Filters Used

[ [0, -1,  0],   Sharpen
  [-1, 5, -1],
  [0, -1,  0] ]

[ [1,  0, -1],   Edge detection
  [1,  0, -1],
  [1,  0, -1] ]

[[-1, -1, -1],   Laplacian
 [-1,  8, -1],
 [-1, -1, -1] ]

๐Ÿ“Š Performance

Metric Value (example)
Accuracy ~90% (binary class)
Epochs 10โ€“50
Dataset Custom / ~8000 imgs

Note that a larger dataset and more training epochs typically lead to higher accuracy.

๐Ÿง  Concepts Demonstrated


๐Ÿ“ฆ Dependencies


๐Ÿ“œ License

MIT License โ€” feel free to use, modify, and share.


๐Ÿค Contributing

PRs are welcome! You can help: