Files
cenet/example/xor.cpp
T

98 lines
2.8 KiB
C++

#include "cenet/layers/dense.hpp"
#include "cenet/loss/mse.hpp"
#include "tulip/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 tulip::matrix<tulip::inline_storage<float>, 1, 1> s_trainData[4] = {};
for (std::size_t i = 0; i < 4; ++i) {
const bool x0 = (i & 1U) != 0;
const bool x1 = (i & 2U) != 0;
s_trainData[i].view().fill(x0 != x1 ? 1.0F : 0.0F);
}
// network net;
using network_type = cenet::network<tulip::matrix<tulip::inline_storage<float>, 1, 2>,
cenet::layers::dense<2>,
cenet::layers::sigmoid,
cenet::layers::dense<1>,
cenet::layers::sigmoid>;
network_type xorNet;
network_type::learning_state learningState;
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;
while (gen <= 10'000'000) {
learningState.reset();
for (std::size_t i = 0; i < 4; ++i) {
tulip::matrix<tulip::inline_storage<float>, 1, 2> xs;
xs.coeff(0) = static_cast<float>(i & 1);
xs.coeff(1) = static_cast<float>(i > 1);
auto output = xorNet.feed(xs, learningState);
auto loss = cenet::loss::mean_squared_error::calculate(s_trainData[i], output);
learningState.backward(xorNet, loss);
}
xorNet.apply(learningState, learning_late);
double acc = 0.0;
for (std::size_t i = 0; i < 4; ++i) {
tulip::matrix<tulip::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].coeff(0);
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;
}