refactor(nn): start migrating layers to cenet::math

This commit is contained in:
2026-11-01 13:20:40 +01:00
parent c65743e957
commit 4b782a6619
2 changed files with 188 additions and 18 deletions
+22 -18
View File
@@ -1,4 +1,6 @@
#include "cenet/layers/dense.hpp"
#include "cenet/loss/mse.hpp"
#include "cenet/math/tensor_fwd.hpp"
#include <cenet/cenet.hpp>
#include <cstddef>
@@ -17,11 +19,11 @@ int main(void) {
};
// network net;
using network_type = cenet::network<cenet::mat<1, 2, float>,
cenet::dense_layer<2>,
cenet::sigmoid_layer,
cenet::dense_layer<1>,
cenet::sigmoid_layer>;
using network_type = cenet::network<cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2>,
cenet::layers::dense<2>,
cenet::layers::sigmoid,
cenet::layers::dense<1>,
cenet::layers::sigmoid>;
network_type xorNet;
static constexpr const char* NETWORK_PATH = "./xor.nn";
@@ -32,36 +34,38 @@ int main(void) {
else
xorNet.fill_random(dist);
static constexpr double EPSILON = 0.5;
static constexpr double learning_late = 0.001;
std::size_t gen = 0;
network_type::learning_state state;
while (gen <= 10'000'000) {
for (std::size_t i = 0; i < 4; ++i) {
cenet::mat<1, 2, float> xs;
xs[0][0] = static_cast<float>(i & 1);
xs[0][1] = static_cast<float>(i > 1);
state.reset();
auto output = xorNet.feed(xs);
for (std::size_t i = 0; i < 4; ++i) {
cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2> xs;
xs.coeff(0) = static_cast<float>(i & 1);
xs.coeff(1) = static_cast<float>(i > 1);
auto output = std::move(xorNet.feed(xs));
auto loss = cenet::loss::mean_squared_error::calculate(s_trainData[i], output);
network_type::learning_state state;
xorNet.backward(loss, state);
xorNet.apply(state, EPSILON);
xorNet.apply(state, learning_late);
}
double acc = 0.0;
for (std::size_t i = 0; i < 4; ++i) {
cenet::mat<1, 2, float> xs;
xs[0][0] = static_cast<float>(i & 1);
xs[0][1] = static_cast<float>(i > 1);
cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2> xs;
xs.coeff(0) = static_cast<float>(i & 1);
xs.coeff(1) = static_cast<float>(i > 1);
float yHat = xorNet.feed(xs)[0][0];
float yHat = xorNet.feed(xs).coeff(0);
float error = yHat - s_trainData[i];
if ((gen % 1000) == 0) {
std::cout << xs[0][0] << " ^ " << xs[0][1] << " = " << yHat << " (error = " << error << ")\n";
std::cout << xs.coeff(0) << " ^ " << xs.coeff(1) << " = " << yHat << " (error = " << error << ")\n";
}
acc += error * error;