Skip to content

Commit 8650dc4

Browse files
authored
Merge pull request #12 from FFMG/feature/python
Initial python module
2 parents c797da8 + 869311c commit 8650dc4

10 files changed

Lines changed: 670 additions & 1 deletion

File tree

.github/workflows/python.yml

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
name: Python Binding CI
2+
3+
on:
4+
push:
5+
branches: [ main ]
6+
pull_request:
7+
branches: [ main ]
8+
9+
jobs:
10+
build-and-verify-python:
11+
runs-on: windows-latest
12+
13+
steps:
14+
- name: Checkout code
15+
uses: actions/checkout@v4
16+
17+
- name: Set up Python 3.12
18+
uses: actions/setup-python@v5
19+
with:
20+
python-version: '3.12'
21+
22+
- name: Install pybind11 dependency
23+
run: |
24+
python -m pip install --upgrade pip
25+
pip install pybind11
26+
27+
- name: Add MSBuild to PATH
28+
uses: microsoft/setup-msbuild@v2
29+
30+
- name: Build Python Binding Module
31+
run: msbuild python/neuralnetwork_py.sln /p:Configuration=Release /p:Platform=x64
32+
env:
33+
PYTHON_HOME: ${{ env.pythonLocation }}
34+
35+
- name: Verify Module Import and Functionality
36+
run: python python/import_check.py

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ All notable changes to the `neural-network` library will be documented in this f
88
- Created the `myoddweb::nn` namespace.
99
- Wrapped all core neural network library classes, structures, and helper functions in the new `myoddweb::nn` namespace (including `NeuralNetwork`, `Layer`, `Neuron`, `activation`, `NeuralNetworkOptions`, etc.).
1010
- Added explicit documentation in the `README.md` explaining how to import and use the new namespace.
11+
- Created a new `/python/` subdirectory containing a C++ binding toolchain (using `pybind11` and NuGet package restore) to compile the C++ library into a Python extension module (`neuralnetwork.pyd`).
12+
- Added a Python test script `example.py` demonstrating how to train and use the neural network from Python.
13+
- Added explicit documentation in `python/README.md` explaining how to build and call the Python module.
1114

1215
### Changed
1316
- Updated all stand-alone example header files in `src/neuralnetwork/examples/` to use the `myoddweb::nn` namespace.

GEMINI.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Gemini Project Context: neural-network
2+
3+
This document provides context and guidelines for interacting with the `neural-network` project.
4+
5+
My name is Florent
6+
7+
## Project Overview
8+
9+
The `neural-network` project is a lightweight, dependency-free Feedforward and Recurrent Neural Network library implemented in modern C++. It is designed for both educational purposes and practical application in financial market analysis and trading.
10+
11+
### Key Features
12+
- **Neural Network Architecture:** Supports standard Feedforward (FF), Elman RNN, and Gated Recurrent Unit (GRU) layers.
13+
- **Advanced Training:** Includes Adam, AdamW, Nadam, and NadamW optimizers, Backpropagation Through Time (BPTT), residual connections, gradient clipping, and dropout (dilution).
14+
- **Learning Rate Strategies:** Implements warmup, exponential decay, periodic restarts with boosts, and adaptive learning rate scheduling.
15+
- **Market Integration:** A dedicated `market` class handles technical indicators (RSI, Bollinger Bands, EMA, MACD, etc.) and data normalization for trading strategies.
16+
- **Visualization:** A built-in `Chart` tool using the `olcPixelGameEngine` for real-time visualization of market data, predictions, and trade signals.
17+
- **Persistence:** Supports saving and loading trained models via a custom serializer.
18+
- **Zero Dependencies:** Built from scratch with minimal external dependencies (embedded `sqlite3`, `TinyJSON`, `olcPixelGameEngine`).
19+
20+
### Technology Stack
21+
- **Language:** C++17/C++20
22+
- **Platform:** Windows (Win32 API for screen metrics, MSVC for compilation)
23+
- **Profiling:** Integrated with Tracy Profiler, disabled by default.
24+
25+
---
26+
27+
## Building and Running
28+
29+
### Prerequisites
30+
- **Visual Studio 2022** (or compatible version) with C++ development workload.
31+
- **Windows OS** (due to Win32 API usage in the charting tool).
32+
- Try and support C++ 99 where possible, comment if not possible.
33+
34+
### Build Instructions
35+
1. Open `examples/neuralnetwork.sln` in Visual Studio.
36+
2. Select the desired configuration (Debug/Release) and platform (x64).
37+
3. Build the solution (`Ctrl+Shift+B`).
38+
39+
### Running the Project
40+
- The primary entry point is `examples/main.cpp`.
41+
42+
### Examples
43+
Multiple standalone examples are located in `examples/`, including:
44+
- `xor.h`: Classic XOR problem.
45+
- `threebitparity.h`: 3-bit parity check.
46+
- `twomoon.h`: Two moons classification.
47+
- `addingproblem.h`: RNN benchmark for long-term dependencies.
48+
49+
- Examples are commented out by default, the user will enable the example(s) needed where and when needed.
50+
51+
---
52+
53+
## Development Conventions
54+
55+
### Coding Style
56+
- Use 2 spaces, never tab.
57+
- **Naming:**
58+
- Classes: `PascalCase` (e.g., `NeuralNetwork`).
59+
- Methods/Functions: `snake_case` (e.g., `train`, `think`).
60+
- Private Members: Prefixed with an underscore (e.g., `_learning_rate`).
61+
- **Headers:** Uses `#pragma once` for include guards.
62+
- **Error Handling:** Uses `Logger` for logging and standard exceptions for critical failures.
63+
64+
### Architecture Patterns
65+
- **Options Pattern:** `NeuralNetworkOptions` uses a builder-like pattern for configuration.
66+
- **RAII:** Strict adherence to RAII for memory and resource management (though some raw pointers are used in legacy parts).
67+
- **Thread Safety:** Uses `std::shared_mutex` for concurrent access to market data and network states.
68+
69+
### Logging and Profiling
70+
- Use `Logger::info`, `Logger::debug`, `Logger::error`, etc., for all output.
71+
- Every new function my start with MYODDWEB_PROFILE_FUNCTION("Name-Of-Class")
72+
- If you see a function that does not have MYODDWEB_PROFILE_FUNCTION("Name-Of-Class") as a first line, please flag it to me.
73+
- **important** The MACRO MYODDWEB_PROFILE_FUNCTION has no impact on performance, when I ask you to review my code for performance, ignore MYODDWEB_PROFILE_FUNCTION as it has no impact.
74+
75+
---
76+
77+
- When looking at the Layer Class, remember to look at all the derived classes.
78+
- Do not worry about Git commits, I will deal will them.
79+
80+
## Key Files
81+
- `include/neuralnetwork/neuralnetwork.h`: The main interface for the NN library.
82+
- `examples/config.json`: Main configuration for the examples runner.
83+
- `examples/strategy.json`: Trading strategy definitions.

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,9 +271,10 @@ For more information on AVX2, see the [Intel Intrinsics Guide](https://www.intel
271271

272272
## Repository Layout
273273

274-
* `\include\neuralnetwork\`: The stand-alone core neural network library (including `/layers/`, `/helpers/`, and `/common/` subdirectories).
274+
* `\include\neuralnetwork\`: The stand-alone core C++ neural network library (including `/layers/`, `/helpers/`, and `/common/` subdirectories).
275275
* `\examples\`: Standalone example implementations, runner (`main.cpp`), and the main Visual Studio solution (`neuralnetwork.sln`).
276276
* `\tests\`: Comprehensive unit test suite.
277+
* `\python\`: Pybind11-based Visual Studio 2022 solution (`neuralnetwork_py.sln`) and Python usage examples.
277278

278279
## Building and Running
279280

python/README.md

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# Python Bindings for neural-network
2+
3+
This subdirectory contains the Visual Studio 2022 C++ project and code necessary to build and run native Python bindings for the `myoddweb::nn` neural network library using `pybind11`.
4+
5+
---
6+
7+
## Folder Layout
8+
9+
* `bindings.cpp`: C++ source file defining the `pybind11` wrapper layer, mapping C++ types, enums, and classes into Python.
10+
* `neuralnetwork_py.vcxproj`: Visual Studio C++ project file configured to build a dynamic library output with a `.pyd` file extension.
11+
* `neuralnetwork_py.vcxproj.filters`: Project filters mapping for Solution Explorer organization.
12+
* `neuralnetwork_py.sln`: Main Visual Studio solution.
13+
* `example.py`: Python script illustrating options configuration, model instantiation, callback monitoring, training, inference, and serialization.
14+
* `import_check.py`: A lightweight validation script that verifies the binary module loads, initializes enums, and starts up correctly (used in CI).
15+
16+
---
17+
18+
## Build Prerequisites
19+
20+
1. **Visual Studio 2022** with the **Desktop development with C++** workload installed.
21+
2. **Python 3.x** (64-bit version recommended, matching the target build platform).
22+
3. **pybind11**: Install the header-only package via `pip`:
23+
```bash
24+
pip install pybind11
25+
```
26+
4. **Environment Setup**:
27+
To allow Visual Studio to locate Python headers (`python.h`) and libraries (`python3x.lib`), you should configure the `PYTHON_HOME` environment variable on your computer:
28+
* Set `PYTHON_HOME` to your Python installation folder (e.g. `C:\Users\<Name>\AppData\Local\Programs\Python\Python312` or `C:\Program Files\Python312`).
29+
* *Alternatively*, if you have Visual Studio's **Python development** workload installed, MSBuild will automatically search for the default Python paths.
30+
31+
---
32+
33+
## Building the Module
34+
35+
1. Open the solution file [neuralnetwork_py.sln](file:///H:/projects/github/neural-network2/python/neuralnetwork_py.sln) in Visual Studio 2022.
36+
2. Set the solution build configuration to:
37+
* **Configuration:** `Release`
38+
* **Platform:** `x64`
39+
3. Build the solution (`Ctrl+Shift+B` or right-click the project -> **Build**).
40+
4. This compiles the library and generates `neuralnetwork.pyd` inside the `python/x64/Release/` folder.
41+
42+
---
43+
44+
## Running the Python Example
45+
46+
Once the `.pyd` module is built, you can run the example script:
47+
48+
```bash
49+
python example.py
50+
```
51+
52+
This script trains a neural network on the XOR classification task and validates predictions.
53+
54+
---
55+
56+
## API Usage Reference
57+
58+
The Python bindings expose the C++ API in a clean, Pythonic wrapper inside the `neuralnetwork` module:
59+
60+
### Enums
61+
* `nn.ActivationMethod`: `Linear`, `Sigmoid`, `Tanh`, `Relu`, `LeakyRelu`, `PRelu`, `Selu`, `Swish`, `Mish`, `Gelu`, `Elu`, `Softmax`.
62+
* `nn.OptimiserType`: `SGD`, `Momentum`, `Nesterov`, `RMSProp`, `Adam`, `AdamW`, `AdaGrad`, `AdaDelta`, `Nadam`, `NadamW`, `AMSGrad`, `LAMB`, `Lion`, `None`.
63+
* `nn.ErrorCalculationType`: `None`, `HuberLoss`, `HuberDirectionLoss`, `MAE`, `MSE`, `RMSE`, `BCELoss`, `CrossEntropy`, etc.
64+
65+
### Core Classes & Properties
66+
* `nn.Activation(method, alpha, temperature=1.0)`: Represents the activation configuration.
67+
* `nn.NeuralNetworkOptions.create(topology)`: Returns a builder options object. Exposes builder methods such as:
68+
* `.with_number_of_epoch(500)`
69+
* `.with_learning_rate(0.15)`
70+
* `.with_batch_size(4)`
71+
* `.with_progress_callback(callback_function)` (allows native Python functions to serve as callbacks during training).
72+
* `nn.NeuralNetwork(options)`: Core model executor. Methods:
73+
* `.train(inputs, outputs)`: Input arguments are standard Python nested lists of floats (e.g. `[[0, 0, 1], [1, 0, 1]]`).
74+
* `.think(inputs)`: Returns predictions as Python lists.
75+
* `nn.NeuralNetworkSerializer`: Exposes static methods:
76+
* `nn.NeuralNetworkSerializer.save(net, filepath)`
77+
* `nn.NeuralNetworkSerializer.load(filepath)` (returns a deserialized network instance).

0 commit comments

Comments
 (0)