feat: introduce generic Neural Network class

This commit is contained in:
2026-09-17 00:14:27 +02:00
parent f8fe507a10
commit a760acc88b
4 changed files with 150 additions and 67 deletions
+2
View File
@@ -2,6 +2,8 @@ cmake_minimum_required(VERSION 3.14)
project(NeuralNetworks CXX) project(NeuralNetworks CXX)
set(CMAKE_CXX_STANDARD 20)
file(GLOB_RECURSE SOURCES src/**.cpp include/**.hpp) file(GLOB_RECURSE SOURCES src/**.cpp include/**.hpp)
add_executable(nn ${SOURCES}) add_executable(nn ${SOURCES})
target_include_directories(nn PRIVATE include/) target_include_directories(nn PRIVATE include/)
+2 -2
View File
@@ -71,9 +71,9 @@ public:
return res; return res;
} }
public: public:
mat_col<N, T> operator[](std::size_t col) { return { m_items + (col * M) }; } mat_col<N, T> operator[](std::size_t col) { return { m_items + (col * N) }; }
mat_col<N, const T> operator[](std::size_t col) const { return { m_items + (col * M) }; } mat_col<N, const T> operator[](std::size_t col) const { return { m_items + (col * N) }; }
public: public:
mat operator+(const mat& rhs) const { mat operator+(const mat& rhs) const {
mat res; mat res;
+134
View File
@@ -0,0 +1,134 @@
#ifndef NN_HPP
#define NN_HPP
#include "mat.hpp"
#include <array>
#include <cstddef>
#include <tuple>
#include <type_traits>
#include <utility>
template <std::size_t N, std::size_t... Layers>
class nn {
private:
template <std::size_t In, std::size_t Out>
struct layer {
static constexpr std::size_t input_count = In;
static constexpr std::size_t output_count = Out;
mat<In, Out> weights;
mat<1, Out> biases;
mat<1, Out> activations;
};
private:
static auto make_output() {
constexpr std::array<std::size_t, sizeof...(Layers) + 1> dims = { N, Layers... };
return mat<1, std::get<sizeof...(Layers)>(dims)>{};
}
public:
using output_type = decltype(make_output());
using input_type = mat<1, N>;
public:
const output_type& get_output() const { return std::get<sizeof...(Layers) - 1>(m_layers).activations; }
public:
template <typename Dist>
void fill_random(const Dist& dist) {
fill_random(dist, std::make_index_sequence<sizeof...(Layers)>{});
}
private:
template <typename Dist, std::size_t... I>
void fill_random(const Dist& dist, std::index_sequence<I...>) {
(fill_random<I>(dist), ...);
}
template <std::size_t I, typename Dist>
void fill_random(const Dist& dist) {
auto& layer = std::get<I>(m_layers);
layer.weights = decltype(layer.weights)::random(dist);
layer.biases = decltype(layer.biases)::random(dist);
}
public:
const output_type& feed(const input_type& input) {
feed(input, std::make_index_sequence<sizeof...(Layers)>{});
return get_output();
}
private:
template <std::size_t... I>
void feed(const input_type& input, std::index_sequence<I...>) {
((feed<I>(input)), ...);
}
template <std::size_t I>
void feed(const input_type& input) {
static constexpr auto input_count = std::tuple_element_t<I, layers_type>::input_count;
static constexpr auto output_count = std::tuple_element_t<I, layers_type>::output_count;
auto& layer = std::get<I>(m_layers);
mat<1, input_count> inputs;
if constexpr (I == 0) {
inputs = input;
} else {
inputs = std::get<I - 1>(m_layers).activations;
}
layer.activations = (inputs * layer.weights) + layer.biases;
for (std::size_t i = 0; i < output_count; ++i) {
layer.activations[0][i] = sigmoid(layer.activations[0][i]);
}
}
public:
void train(const input_type& input, const output_type& expected, double learningRate) {
feed(input);
auto outputErr = (get_output() - expected).hadamard(get_output()).hadamard(1.0 - get_output());
train_chain<sizeof...(Layers) - 1>(input, learningRate, outputErr);
}
private:
template <std::size_t I, typename ErrorType>
void train_chain(const input_type& input, double learningRate, ErrorType error) {
auto next = train<I>(input, learningRate, error);
if constexpr (I > 0) {
train_chain<I - 1>(input, learningRate, next);
}
}
template <std::size_t I, typename ErrorType>
auto train(const input_type& input, double learningRate, ErrorType prevErr) {
auto& layer = std::get<I>(m_layers);
const auto& layerInput = get_layer_input<I>(input);
layer.weights -= learningRate * (layerInput.transpose() * prevErr);
layer.biases -= learningRate * prevErr;
auto backpropErr = prevErr * layer.weights.transpose();
if constexpr (I > 0) {
return backpropErr.hadamard(layerInput.hadamard(1.0 - layerInput));
} else {
return backpropErr;
}
}
private:
template <std::size_t I>
const auto& get_layer_input(const input_type& input) {
if constexpr (I == 0) {
return input;
} else {
return std::get<I - 1>(m_layers).activations;
}
}
private:
template <std::size_t... I>
static auto make_layers_tuple(std::index_sequence<I...>) {
constexpr std::array<std::size_t, sizeof...(Layers) + 1> dims = { N, Layers... };
return std::tuple<layer<std::get<I>(dims), std::get<I + 1>(dims)>...>{};
}
private:
static double sigmoid(double input) { return 1 / (1 + std::exp(-input)); }
private:
using layers_type = decltype(make_layers_tuple(std::make_index_sequence<sizeof...(Layers)>{}));
layers_type m_layers;
};
#endif // NN_HPP
+12 -65
View File
@@ -1,4 +1,4 @@
#include "mat.hpp" #include "nn.hpp"
#include <cmath> #include <cmath>
#include <cstddef> #include <cstddef>
@@ -11,58 +11,6 @@ static double sigmoid(double input) {
static std::uniform_real_distribution<> dist(-1, 1); static std::uniform_real_distribution<> dist(-1, 1);
struct network {
mat<2, 2> hiddenWeights = mat<2, 2>::random(dist);
mat<1, 2> hiddenBiases = mat<1, 2>::random(dist);
mat<1, 2> hiddenOutputs;
mat<2, 1> outputWeights = mat<2, 1>::random(dist);
mat<1, 1> outputBiases = mat<1, 1>::random(dist);
mat<1, 1> output;
void feed(const mat<1, 2>& xs) {
hidden(xs);
output[0][0] = sigmoid(((hiddenOutputs * outputWeights) + outputBiases)[0][0]);
}
void apply(const mat<1, 2>& xs, double yHat, double yEx, double eps) {
auto outputErr = (yHat - yEx) * yHat * (1 - yHat);
auto owGradient = hiddenOutputs.transpose() * outputErr;
auto backpropErr = outputErr * outputWeights.transpose();
auto hiddenErr = backpropErr.hadamard((hiddenOutputs.hadamard(1.0 - hiddenOutputs)));
auto hwGradient = xs.transpose() * hiddenErr;
outputWeights -= eps * owGradient;
outputBiases -= mat<1, 1>{ eps * outputErr };
hiddenWeights -= eps * hwGradient;
hiddenBiases -= eps * hiddenErr;
// double h1Comp = h1(x1, x2);
// double h1Sq = h1Comp * h1Comp;
// double h2Comp = h2(x1, x2);
// double h2Sq = h2Comp * h2Comp;
// double dZ21 = (yHat - yEx) * yHat * (1.0 - yHat);
// double dZ11 = dZ21 * l2ws[0] * h1Comp * (1.0 - h1Comp);
// double dZ12 = dZ21 * l2ws[1] * h2Comp * (1.0 - h2Comp);
// l1ws[0] -= eps * dZ11 * x1;
// l1ws[1] -= eps * dZ12 * x1;
// l1ws[2] -= eps * dZ11 * x2;
// l1ws[3] -= eps * dZ12 * x2;
// l1bs[0] -= eps * dZ11;
// l1bs[1] -= eps * dZ12;
// l2ws[0] -= eps * dZ21 * h1Comp;
// l2ws[1] -= eps * dZ21 * h2Comp;
// l2bs[0] -= eps * dZ21;
}
private:
void hidden(const mat<1, 2>& xs) {
hiddenOutputs = (xs * hiddenWeights) + hiddenBiases;
for (std::size_t i = 0; i < 2; ++i)
hiddenOutputs[0][i] = sigmoid(hiddenOutputs[0][i]);
}
};
int main(void) { int main(void) {
static constexpr double s_trainData[4] = { static constexpr double s_trainData[4] = {
0, // 0 ^ 0 0, // 0 ^ 0
@@ -71,23 +19,21 @@ int main(void) {
0, // 1 ^ 1 0, // 1 ^ 1
}; };
network net; // network net;
nn<2, 2, 1> xorNet;
xorNet.fill_random(dist);
static constexpr double EPSILON = 0.2; static constexpr double EPSILON = 0.5;
std::size_t gen = 0; std::size_t gen = 0;
while (gen++ < 100'000) { while (gen <= 100'000) {
for (std::size_t i = 0; i < 4; ++i) { for (std::size_t i = 0; i < 4; ++i) {
mat<1, 2> xs; mat<1, 2> xs;
xs[0][0] = static_cast<double>(i & 1); xs[0][0] = static_cast<double>(i & 1);
xs[0][1] = static_cast<double>(i > 1); xs[0][1] = static_cast<double>(i > 1);
net.feed(xs); xorNet.train(xs, s_trainData[i], EPSILON);
double yHat = net.output[0][0];
net.apply(xs, yHat, s_trainData[i], EPSILON);
} }
double acc = 0.0; double acc = 0.0;
@@ -97,11 +43,10 @@ int main(void) {
xs[0][0] = static_cast<double>(i & 1); xs[0][0] = static_cast<double>(i & 1);
xs[0][1] = static_cast<double>(i > 1); xs[0][1] = static_cast<double>(i > 1);
net.feed(xs); double yHat = xorNet.feed(xs)[0][0];
double yHat = net.output[0][0];
double error = yHat - s_trainData[i]; double error = yHat - s_trainData[i];
if ((gen % 100) == 0) { if ((gen % 10) == 0) {
std::cout << xs[0][0] << " ^ " << xs[0][1] << " = " << yHat << " (error = " << error << ")\n"; std::cout << xs[0][0] << " ^ " << xs[0][1] << " = " << yHat << " (error = " << error << ")\n";
} }
@@ -110,9 +55,11 @@ int main(void) {
double cost = acc / 8.0; double cost = acc / 8.0;
if (gen % 100 == 0) { if (gen % 10 == 0) {
std::cout << "Generation " << gen << ", cost = " << cost << '\n'; std::cout << "Generation " << gen << ", cost = " << cost << '\n';
} }
++gen;
} }
return 0; return 0;