refactor(nn): start migrating layers to cenet::math
This commit is contained in:
+22
-18
@@ -1,4 +1,6 @@
|
|||||||
|
#include "cenet/layers/dense.hpp"
|
||||||
#include "cenet/loss/mse.hpp"
|
#include "cenet/loss/mse.hpp"
|
||||||
|
#include "cenet/math/tensor_fwd.hpp"
|
||||||
|
|
||||||
#include <cenet/cenet.hpp>
|
#include <cenet/cenet.hpp>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
@@ -17,11 +19,11 @@ int main(void) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// network net;
|
// network net;
|
||||||
using network_type = cenet::network<cenet::mat<1, 2, float>,
|
using network_type = cenet::network<cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2>,
|
||||||
cenet::dense_layer<2>,
|
cenet::layers::dense<2>,
|
||||||
cenet::sigmoid_layer,
|
cenet::layers::sigmoid,
|
||||||
cenet::dense_layer<1>,
|
cenet::layers::dense<1>,
|
||||||
cenet::sigmoid_layer>;
|
cenet::layers::sigmoid>;
|
||||||
network_type xorNet;
|
network_type xorNet;
|
||||||
|
|
||||||
static constexpr const char* NETWORK_PATH = "./xor.nn";
|
static constexpr const char* NETWORK_PATH = "./xor.nn";
|
||||||
@@ -32,36 +34,38 @@ int main(void) {
|
|||||||
else
|
else
|
||||||
xorNet.fill_random(dist);
|
xorNet.fill_random(dist);
|
||||||
|
|
||||||
static constexpr double EPSILON = 0.5;
|
static constexpr double learning_late = 0.001;
|
||||||
|
|
||||||
std::size_t gen = 0;
|
std::size_t gen = 0;
|
||||||
|
|
||||||
|
network_type::learning_state state;
|
||||||
while (gen <= 10'000'000) {
|
while (gen <= 10'000'000) {
|
||||||
for (std::size_t i = 0; i < 4; ++i) {
|
state.reset();
|
||||||
cenet::mat<1, 2, float> xs;
|
|
||||||
xs[0][0] = static_cast<float>(i & 1);
|
|
||||||
xs[0][1] = static_cast<float>(i > 1);
|
|
||||||
|
|
||||||
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);
|
auto loss = cenet::loss::mean_squared_error::calculate(s_trainData[i], output);
|
||||||
|
|
||||||
network_type::learning_state state;
|
|
||||||
xorNet.backward(loss, state);
|
xorNet.backward(loss, state);
|
||||||
xorNet.apply(state, EPSILON);
|
xorNet.apply(state, learning_late);
|
||||||
}
|
}
|
||||||
|
|
||||||
double acc = 0.0;
|
double acc = 0.0;
|
||||||
|
|
||||||
for (std::size_t i = 0; i < 4; ++i) {
|
for (std::size_t i = 0; i < 4; ++i) {
|
||||||
cenet::mat<1, 2, float> xs;
|
cenet::math::matrix<cenet::math::inline_storage<float>, 1, 2> xs;
|
||||||
xs[0][0] = static_cast<float>(i & 1);
|
xs.coeff(0) = static_cast<float>(i & 1);
|
||||||
xs[0][1] = 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];
|
float error = yHat - s_trainData[i];
|
||||||
|
|
||||||
if ((gen % 1000) == 0) {
|
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;
|
acc += error * error;
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
/**
|
||||||
|
* The "dense" layer class.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef CENET_LAYERS_DENSE_HPP
|
||||||
|
#define CENET_LAYERS_DENSE_HPP
|
||||||
|
|
||||||
|
#include "../layer.hpp"
|
||||||
|
#include "../math/tensor_fwd.hpp"
|
||||||
|
#include "../network.hpp"
|
||||||
|
|
||||||
|
namespace cenet {
|
||||||
|
namespace layers {
|
||||||
|
|
||||||
|
// TODO: redesign the layer interface after porting the old layers
|
||||||
|
template <std::size_t Features>
|
||||||
|
class dense final : public layer_info {
|
||||||
|
template <typename Input, typename... Layers>
|
||||||
|
friend class ::cenet::network;
|
||||||
|
private:
|
||||||
|
template <class NN, std::size_t I>
|
||||||
|
struct inner final {
|
||||||
|
using input_type = typename input_type_s<NN, I>::type;
|
||||||
|
using value_type = typename input_type::value_type;
|
||||||
|
using output_type = math::matrix<value_type, 1, Features>;
|
||||||
|
|
||||||
|
static constexpr auto input_cols = input_type::shape_type::template sget<1>();
|
||||||
|
|
||||||
|
using weights_type = math::matrix<math::inline_storage<value_type>, input_cols, Features>;
|
||||||
|
using biases_type = math::matrix<math::inline_storage<value_type>, 1, Features>;
|
||||||
|
|
||||||
|
struct gradient final {
|
||||||
|
using parent_type = inner;
|
||||||
|
|
||||||
|
weights_type weights;
|
||||||
|
biases_type biases;
|
||||||
|
|
||||||
|
// TODO: move Adam into optimizer state
|
||||||
|
weights_type momentumWeights;
|
||||||
|
biases_type momentumBiases;
|
||||||
|
weights_type varianceWeights;
|
||||||
|
biases_type varianceBiases;
|
||||||
|
|
||||||
|
std::size_t time = 0;
|
||||||
|
|
||||||
|
void reset() {
|
||||||
|
weights.view().fill();
|
||||||
|
biases.view().fill();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
weights_type weights;
|
||||||
|
biases_type biases;
|
||||||
|
|
||||||
|
typename input_type::template with_storage<math::inline_storage_tag> retained;
|
||||||
|
|
||||||
|
void dump(std::ostream& os) const {
|
||||||
|
os.write(reinterpret_cast<const char*>(weights.data()), sizeof(value_type) * weights.size());
|
||||||
|
os.write(reinterpret_cast<const char*>(biases.data()), sizeof(value_type) * biases.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
void load(std::istream& is) {
|
||||||
|
is.read(reinterpret_cast<char*>(weights.data()), sizeof(value_type) * weights.size());
|
||||||
|
is.read(reinterpret_cast<char*>(biases.data()), sizeof(value_type) * biases.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Dist>
|
||||||
|
void fill_random(const Dist& dist) {
|
||||||
|
value_type scale = std::sqrt(2.0 / static_cast<value_type>(input_cols));
|
||||||
|
weights.view().fill_random(dist);
|
||||||
|
weights = weights.apply([scale](auto val) { return val * scale; });
|
||||||
|
biases.view().fill();
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Fwd>
|
||||||
|
auto feed(Fwd&& fwd) {
|
||||||
|
retained = std::forward<Fwd>(fwd);
|
||||||
|
return retained.matmul(weights) + biases;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Error>
|
||||||
|
auto backward(gradient& grad, Error&& prevErr) {
|
||||||
|
grad.weights += retained.transpose().matmul(prevErr);
|
||||||
|
grad.biases += prevErr;
|
||||||
|
|
||||||
|
return std::forward<Error>(prevErr).matmul(weights.transpose());
|
||||||
|
}
|
||||||
|
|
||||||
|
void apply_grad(gradient& grad, double divisor, double rate) {
|
||||||
|
++grad.time;
|
||||||
|
|
||||||
|
constexpr double beta1 = 0.9;
|
||||||
|
constexpr double beta2 = 0.999;
|
||||||
|
constexpr double epsilon = 1e-8;
|
||||||
|
|
||||||
|
for (std::size_t row = 0; row < input_cols; ++row) {
|
||||||
|
for (std::size_t col = 0; col < Features; ++col) {
|
||||||
|
auto avgGrad = grad.weights[row][col] / divisor;
|
||||||
|
|
||||||
|
grad.momentumWeights[row][col] = beta1 * grad.momentumWeights[row][col] + (1.0 - beta1) * avgGrad;
|
||||||
|
grad.varianceWeights[row][col] =
|
||||||
|
beta2 * grad.varianceWeights[row][col] + (1.0 - beta2) * (avgGrad * avgGrad);
|
||||||
|
|
||||||
|
auto momentumCorrected = grad.momentumWeights[row][col] / (1.0 - std::pow(beta1, grad.time));
|
||||||
|
auto varianceCorrected = grad.varianceWeights[row][col] / (1.0 - std::pow(beta2, grad.time));
|
||||||
|
|
||||||
|
weights[row][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (std::size_t col = 0; col < Features; ++col) {
|
||||||
|
double avgGrad = grad.biases[0][col] / divisor;
|
||||||
|
|
||||||
|
grad.momentumBiases[0][col] = beta1 * grad.momentumBiases[0][col] + (1.0 - beta1) * avgGrad;
|
||||||
|
grad.varianceBiases[0][col] = beta2 * grad.varianceBiases[0][col] + (1.0 - beta2) * (avgGrad * avgGrad);
|
||||||
|
|
||||||
|
auto momentumCorrected = grad.momentumBiases[0][col] / (1.0 - std::pow(beta1, grad.time));
|
||||||
|
auto varianceCorrected = grad.varianceBiases[0][col] / (1.0 - std::pow(beta2, grad.time));
|
||||||
|
|
||||||
|
biases[0][col] -= (rate * momentumCorrected) / (std::sqrt(varianceCorrected) + epsilon);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
class sigmoid final : public layer_info {
|
||||||
|
template <typename Input, typename... Layers>
|
||||||
|
friend class ::cenet::network;
|
||||||
|
private:
|
||||||
|
template <class NN, std::size_t I>
|
||||||
|
struct inner final {
|
||||||
|
using input_type = typename input_type_s<NN, I>::type;
|
||||||
|
using output_type = input_type;
|
||||||
|
|
||||||
|
typename output_type::template with_storage<math::inline_storage_tag> retained;
|
||||||
|
|
||||||
|
struct gradient {
|
||||||
|
void reset() {}
|
||||||
|
};
|
||||||
|
|
||||||
|
void dump(std::ostream& os) const {}
|
||||||
|
|
||||||
|
void load(std::istream& is) {}
|
||||||
|
|
||||||
|
template <typename Dist>
|
||||||
|
void fill_random(const Dist& dist) {}
|
||||||
|
|
||||||
|
template <typename Fwd>
|
||||||
|
auto feed(Fwd&& fwd) {
|
||||||
|
return retained = std::forward<Fwd>(fwd).apply([](auto in) { return 1 / (1 + std::exp(-in)); });
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Error>
|
||||||
|
auto backward(gradient& grad, Error&& prevErr) const {
|
||||||
|
return std::forward<Error>(prevErr) * retained *
|
||||||
|
(static_cast<typename output_type::value_type>(1) - retained);
|
||||||
|
}
|
||||||
|
|
||||||
|
void apply_grad(gradient&, double, double) {}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace layers
|
||||||
|
} // namespace cenet
|
||||||
|
|
||||||
|
#endif // CENET_LAYERS_DENSE_HPP
|
||||||
Reference in New Issue
Block a user