91 lines
2.4 KiB
C++
91 lines
2.4 KiB
C++
#include "cenet/loss/mse.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::mat<1, 2, float>,
|
|
cenet::dense_layer<2>,
|
|
cenet::sigmoid_layer,
|
|
cenet::dense_layer<1>,
|
|
cenet::sigmoid_layer>;
|
|
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 EPSILON = 0.5;
|
|
|
|
std::size_t gen = 0;
|
|
|
|
while (gen <= 10'000'000) {
|
|
for (std::size_t i = 0; i < 4; ++i) {
|
|
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);
|
|
auto loss = cenet::loss::mean_squared_error::calculate(s_trainData[i], output);
|
|
|
|
network_type::learning_state state;
|
|
xorNet.backward(loss, state);
|
|
xorNet.apply(state, EPSILON);
|
|
}
|
|
|
|
double acc = 0.0;
|
|
|
|
for (std::size_t i = 0; i < 4; ++i) {
|
|
cenet::mat<1, 2, float> xs;
|
|
xs[0][0] = static_cast<float>(i & 1);
|
|
xs[0][1] = static_cast<float>(i > 1);
|
|
|
|
float yHat = xorNet.feed(xs)[0][0];
|
|
float error = yHat - s_trainData[i];
|
|
|
|
if ((gen % 1000) == 0) {
|
|
std::cout << xs[0][0] << " ^ " << xs[0][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;
|
|
}
|