From 7b891865999901df693473070299f43b9344b750 Mon Sep 17 00:00:00 2001 From: CHatingPython Date: Thu, 17 Sep 2026 21:56:22 +0200 Subject: [PATCH] feat: add network saving and loading --- include/mat.hpp | 6 ++++++ include/nn.hpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/include/mat.hpp b/include/mat.hpp index ea7e8be..9f73046 100644 --- a/include/mat.hpp +++ b/include/mat.hpp @@ -138,6 +138,12 @@ public: return res; } +public: + T* data() { return m_items; } + + const T* data() const { return m_items; } + + constexpr std::size_t size() const { return M * N; } private: T m_items[M * N]; }; diff --git a/include/nn.hpp b/include/nn.hpp index 46dd1b3..b17bbf7 100644 --- a/include/nn.hpp +++ b/include/nn.hpp @@ -5,6 +5,8 @@ #include #include +#include +#include #include #include #include @@ -31,6 +33,34 @@ public: using input_type = mat<1, N>; public: const output_type& get_output() const { return std::get(m_layers).activations; } +public: + void dump_network(std::ostream& os) const { dump_network(os, std::make_index_sequence{}); } +private: + template + void dump_network(std::ostream& os, std::index_sequence) const { + (dump_layer(os), ...); + } + + template + void dump_layer(std::ostream& os) const { + const auto& layer = std::get(m_layers); + os.write(reinterpret_cast(layer.weights.data()), sizeof(double) * layer.weights.size()); + os.write(reinterpret_cast(layer.biases.data()), sizeof(double) * layer.biases.size()); + } +public: + void load_network(std::istream& is) { load_network(is, std::make_index_sequence{}); } +private: + template + void load_network(std::istream& is, std::index_sequence) { + (load_layer(is), ...); + } + + template + void load_layer(std::istream& is) { + auto& layer = std::get(m_layers); + is.read(reinterpret_cast(layer.weights.data()), sizeof(double) * layer.weights.size()); + is.read(reinterpret_cast(layer.biases.data()), sizeof(double) * layer.biases.size()); + } public: template void fill_random(const Dist& dist) {