Files
cenet/example/xor.cpp
T

96 lines
2.7 KiB
C++

#include "cenet/layers/dense.hpp"
#include "cenet/loss/mse.hpp"
#include "cenet/math/tensor_fwd.hpp"
#include <cenet/cenet.hpp>
#include <cstddef>
#include <fstream>
#include <iostream>
#include <random>
static std::uniform_real_distribution<> dist(-1, 1);
int main(void) {
static constexpr float s_trainData[4] = {
0, // 0 ^ 0
1, // 1 ^ 0
1, // 0 ^ 1
0, // 1 ^ 1
};
// network net;
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";
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 learning_late = 0.5;
std::size_t gen = 0;
network_type::learning_state state;
while (gen <= 10'000'000) {
state.reset();
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);
xorNet.backward(loss, state);
}
xorNet.apply(state, learning_late);
double acc = 0.0;
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);
float yHat = xorNet.feed(xs).coeff(0);
float error = yHat - s_trainData[i];
if ((gen % 1000) == 0) {
std::cout << xs.coeff(0) << " ^ " << xs.coeff(1) << " = " << yHat << " (error = " << error << ")\n";
}
acc += error * error;
}
static constexpr double LOWER_COST = 1e-5;
double cost = acc / 8.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;
}
return 0;
}