Metadata-Version: 2.4
Name: simplegrade
Version: 0.1.7
Summary: A lightweight PyTorch-inspired autograd library built from scratch
Home-page: https://github.com/mohamedrxo/simplegrad
Author: Mohamed Rachoum
Author-email: mohamedrxo4@gmail.com
License: MIT
Project-URL: Source, https://github.com/mohamedrxo/simplegrad
Project-URL: Bug Tracker, https://github.com/mohamedrxo/simplegrad/issues
Project-URL: PyPI, https://pypi.org/project/simplegrade/
Keywords: python,deep-learning,machine-learning,autograd,neural-networks,pytorch,tensor,education,ai
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.7
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# SimpleGrade

[![PyPI version](https://img.shields.io/pypi/v/simplegrade)](https://pypi.org/project/simplegrade/)
[![PyPI Downloads](https://img.shields.io/pypi/dm/simplegrade)](https://pypi.org/project/simplegrade/)
[![GitHub stars](https://img.shields.io/github/stars/mohamedrxo/simplegrad?style=social)](https://github.com/mohamedrxo/simplegrad)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

SimpleGrade is a lightweight Python library inspired by PyTorch and Tinygrad. It provides automatic differentiation and the core components required to build and train neural networks from scratch, making it an educational framework for understanding how deep learning libraries work internally.

## Installation

Install the latest release from PyPI:

```bash
pip install simplegrade
```

Or install the latest development version from GitHub:

```bash
git clone https://github.com/mohamedrxo/simplegrad.git
cd simplegrad
pip install -e .
```

## Features

- Automatic differentiation (Autograd)
- Tensor operations
- Neural network building blocks
- Linear layers
- Loss functions
- SGD optimizer
- DataLoader
- NumPy-based implementation
- Lightweight and easy to understand

## Example

```python
from simplegrade import Tensor

a = Tensor([[1, 2, 3]], requires_grad=True)
b = Tensor([[2, 1, 0]], requires_grad=True)

c = a + b
d = a * b
loss = d.sum()

loss.backward()

print("Loss:", loss)
print("Gradient of a:", a.grad)
print("Gradient of b:", b.grad)
```
## Complete Example — Training a Neural Network on MNIST
```python
from simplegrade import Tensor, SGD ,MSELoss,Linear,DataLoader
import pandas as pd
import kagglehub
import matplotlib.pyplot as plt
import random
import numpy as np
import pandas as pd


# Downloading the MNIST Dataset from kaggle
path = kagglehub.dataset_download("oddrationale/mnist-in-csv")
print("Path to dataset files:", path)

train = pd.read_csv(f"{path}/mnist_train.csv")
test = pd.read_csv(f"{path}/mnist_test.csv")

# spliting images and labels
images = train.values[:,1:]
labels = train.values[:,0]

#passing the data to a dataloader
traing_data = DataLoader(images,labels)

# Defining the MNIST Model Class
class MNISTModel():
    def __init__(self,in_features,hidden_features, out_features):
        self.linear1 = Linear(in_features, hidden_features,bias=True)
        self.linear2 = Linear(hidden_features, out_features,bias=True)
    def __call__(self, x):
        x = self.linear1(x)
        x = x.relu()
        x = self.linear2(x)
        return  x

    def parameters(self):
        return self.linear1.parameters() + self.linear2.parameters()

# Creating the model
model = MNISTModel(784,100,10)

# Creating the MSELoss and SGD optimizer
criterion  = MSELoss()
optimizer = SGD(model.parameters(),lr=0.01)

# The Training Loop
for i in range(10000):
    # every batch contain 20 samples from the MNIST Dataset
    batch = traing_data(20)
    input_images = Tensor(batch['data']/ 255.0)
    labels = Tensor.one_hotencoding(batch['label'],  10)

    predictions = model(input_images)
    predictions = predictions.softmax()
    loss = criterion(predictions,labels)
    loss.backward()
    print("batch: ",i+1,'loss: ',f"{loss.item():.5f}")
    optimizer.step()
    optimizer.zero_grad()


# Testing The Model
batch = traing_data(6)
input_images = Tensor(batch['data'] / 255.0)
labels = Tensor.one_hotencoding(batch['label'], 10)

# Grid layout
n_images = batch['data'].shape[0]
cols = 3  # 3 images per row
rows = (n_images + cols - 1) // cols

fig, axes = plt.subplots(rows, cols, figsize=(cols * 3, rows * 3))
axes = axes.flatten()

for i in range(n_images):
    test_image = batch['data'][i]
    resized_img = test_image.reshape((28, 28))
    label = batch['label'][i]

    # Model prediction
    prediction = model(Tensor(np.expand_dims(test_image, axis=0)))
    prediction = prediction.softmax() * 100
    prediction = prediction.data.squeeze()
    pred_class = np.argmax(prediction)
    pred_prob = np.max(prediction)

    axes[i].imshow(resized_img, cmap="gray")
    axes[i].set_title(f"True: {label}\nPred: {pred_class} ({pred_prob:.1f}%)")
    axes[i].axis("off")

# Hide any unused axes
for j in range(n_images, len(axes)):
    axes[j].axis("off")

plt.tight_layout()
plt.show()
```
## Project Links

- **PyPI:** https://pypi.org/project/simplegrade/
- **GitHub:** https://github.com/mohamedrxo/simplegrad
- **Issues:** https://github.com/mohamedrxo/simplegrad/issues

## Contributing

Contributions, bug reports, feature requests, and suggestions are welcome. If you find this project useful, consider starring the repository on GitHub.
