From 32bb5a98f5cdbc5e83ead4aedc8af4e6de942d08 Mon Sep 17 00:00:00 2001 From: CHatingPython Date: Thu, 17 Sep 2026 21:56:40 +0200 Subject: [PATCH] refactor: change the project structure --- CMakeLists.txt | 5 ++--- src/{main.cpp => xor.cpp} | 26 ++++++++++++++++++++++---- 2 files changed, 24 insertions(+), 7 deletions(-) rename src/{main.cpp => xor.cpp} (65%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 70ee656..3018683 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,6 +4,5 @@ project(NeuralNetworks CXX) set(CMAKE_CXX_STANDARD 20) -file(GLOB_RECURSE SOURCES src/**.cpp include/**.hpp) -add_executable(nn ${SOURCES}) -target_include_directories(nn PRIVATE include/) +add_executable(xor src/xor.cpp) +target_include_directories(xor PRIVATE include/) diff --git a/src/main.cpp b/src/xor.cpp similarity index 65% rename from src/main.cpp rename to src/xor.cpp index 7c1724e..78160ee 100644 --- a/src/main.cpp +++ b/src/xor.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -21,13 +22,20 @@ int main(void) { // network net; nn<2, 2, 1> xorNet; - xorNet.fill_random(dist); + + static constexpr const char* NETWORK_PATH = "./xor.nn"; + + std::ifstream file(NETWORK_PATH, std::ios::in | std::ios::binary); + if (file.is_open()) + xorNet.load_network(file); + else + xorNet.fill_random(dist); static constexpr double EPSILON = 0.5; std::size_t gen = 0; - while (gen <= 100'000) { + while (gen <= 10'000'000) { for (std::size_t i = 0; i < 4; ++i) { mat<1, 2> xs; xs[0][0] = static_cast(i & 1); @@ -46,19 +54,29 @@ int main(void) { double yHat = xorNet.feed(xs)[0][0]; double error = yHat - s_trainData[i]; - if ((gen % 10) == 0) { + if ((gen % 1000) == 0) { std::cout << xs[0][0] << " ^ " << xs[0][1] << " = " << yHat << " (error = " << error << ")\n"; } acc += error * error; } + static constexpr double LOWER_COST = 1e-5; + double cost = acc / 8.0; - if (gen % 10 == 0) { + if ((gen % 1000) == 0 || cost <= LOWER_COST) { std::cout << "Generation " << gen << ", cost = " << cost << '\n'; } + if (cost <= LOWER_COST) { + std::ofstream outFile(NETWORK_PATH, std::ios::out | std::ios::binary); + if (!outFile.is_open()) break; + xorNet.dump_network(outFile); + std::cout << "Saved the network to " << NETWORK_PATH << "!\n"; + break; + } + ++gen; }