#ifndef NN_HPP #define NN_HPP #include "mat.hpp" #include #include #include #include #include #include #include #include template class nn { private: template struct gradient { static constexpr std::size_t input_count = In; static constexpr std::size_t output_count = Out; mat weights; mat<1, Out> biases; mat momentumWeights; mat<1, Out> momentumBiases; mat varianceWeights; mat<1, Out> varianceBiases; std::size_t time = 0; void reset() { weights = mat{}; biases = mat<1, Out>{}; } }; template struct layer { static constexpr std::size_t input_count = In; static constexpr std::size_t output_count = Out; mat weights; mat<1, Out> biases; mat<1, Out> activations; void apply(gradient& gradient, double divisor, double rate) { ++gradient.time; constexpr double beta1 = 0.9; constexpr double beta2 = 0.999; constexpr double epsilon = 1e-8; for (std::size_t row = 0; row < In; ++row) { for (std::size_t col = 0; col < Out; ++col) { double avgGrad = gradient.weights[row][col] / divisor; gradient.momentumWeights[row][col] = beta1 * gradient.momentumWeights[row][col] + (1.0 - beta1) * avgGrad; gradient.varianceWeights[row][col] = beta2 * gradient.varianceWeights[row][col] + (1.0 - beta2) * (avgGrad * avgGrad); double momentumCorrected = gradient.momentumWeights[row][col] / (1.0 - std::pow(beta1, gradient.time)); double varianceCorrected = gradient.varianceWeights[row][col] / (1.0 - std::pow(beta2, gradient.time)); weights[row][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon); } } for (std::size_t col = 0; col < Out; ++col) { double avgGrad = gradient.biases[0][col] / divisor; gradient.momentumBiases[0][col] = beta1 * gradient.momentumBiases[0][col] + (1.0 - beta1) * avgGrad; gradient.varianceBiases[0][col] = beta2 * gradient.varianceBiases[0][col] + (1.0 - beta2) * (avgGrad * avgGrad); double momentumCorrected = gradient.momentumBiases[0][col] / (1.0 - std::pow(beta1, gradient.time)); double varianceCorrected = gradient.varianceBiases[0][col] / (1.0 - std::pow(beta2, gradient.time)); biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon); } } }; private: static auto make_output() { constexpr std::array dims = { N, Layers... }; return mat<1, std::get(dims)>{}; } public: using output_type = decltype(make_output()); 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) { fill_random(dist, std::make_index_sequence{}); } private: template void fill_random(const Dist& dist, std::index_sequence) { (fill_random(dist), ...); } template void fill_random(const Dist& dist) { auto& layer = std::get(m_layers); double scale = std::sqrt(2.0 / static_cast(std::tuple_element_t::input_count)); layer.weights = decltype(layer.weights)::random(dist) * scale; layer.biases = decltype(layer.biases)::random(dist) * scale; } public: const output_type& feed(const input_type& input) { feed(input, std::make_index_sequence{}); return get_output(); } private: template void feed(const input_type& input, std::index_sequence) { ((feed(input)), ...); } template void feed(const input_type& input) { static constexpr auto input_count = std::tuple_element_t::input_count; static constexpr auto output_count = std::tuple_element_t::output_count; auto& layer = std::get(m_layers); mat<1, input_count> inputs; if constexpr (I == 0) { inputs = input; } else { inputs = std::get(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]); } } private: template static auto make_gradients_tuple(std::index_sequence) { constexpr std::array dims = { N, Layers... }; return std::tuple(dims), std::get(dims)>...>{}; } public: struct learning_state final { friend class nn; void reset() { m_count = 0; reset(std::make_index_sequence{}); } private: template void reset(std::index_sequence) { (std::get(m_layers).reset(), ...); } private: std::size_t m_count = 0; decltype(make_gradients_tuple(std::make_index_sequence{})) m_layers; }; public: void backprop(const input_type& input, const output_type& expected, learning_state& state) { feed(input); auto outputErr = (get_output() - expected).hadamard(get_output()).hadamard(1.0 - get_output()); backprop_chain(input, state, outputErr); state.m_count += 1; } private: template void backprop_chain(const input_type& input, learning_state& state, ErrorType error) { auto next = backprop(input, state, error); if constexpr (I > 0) { backprop_chain(input, state, next); } } template auto backprop(const input_type& input, learning_state& state, ErrorType prevErr) { const auto& layer = std::get(m_layers); auto& gradient = std::get(state.m_layers); const auto& layerInput = get_layer_input(input); gradient.weights += layerInput.transpose() * prevErr; gradient.biases += prevErr; auto backpropErr = prevErr * layer.weights.transpose(); if constexpr (I > 0) { return backpropErr.hadamard(layerInput.hadamard(1.0 - layerInput)); } else { return backpropErr; } } public: void apply(learning_state& state, double rate) { apply(state, rate, std::make_index_sequence{}); } private: template void apply(learning_state& state, double rate, std::index_sequence) { (std::get(m_layers).apply(std::get(state.m_layers), state.m_count, rate), ...); } public: void train(const input_type& input, const output_type& expected, double learningRate) { learning_state state; backprop(input, expected, state); apply(state, learningRate); } private: template const auto& get_layer_input(const input_type& input) { if constexpr (I == 0) { return input; } else { return std::get(m_layers).activations; } } private: template static auto make_layers_tuple(std::index_sequence) { constexpr std::array dims = { N, Layers... }; return std::tuple(dims), std::get(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{})); layers_type m_layers; }; #endif // NN_HPP