89 lines
2.3 KiB
C++
89 lines
2.3 KiB
C++
#include <cenet/nn.hpp>
|
|
#include <cmath>
|
|
#include <cstddef>
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <random>
|
|
|
|
static double sigmoid(double input) {
|
|
return 1 / (1 + std::exp(-input));
|
|
}
|
|
|
|
static std::uniform_real_distribution<> dist(-1, 1);
|
|
|
|
int main(void) {
|
|
static constexpr double s_trainData[4] = {
|
|
0, // 0 ^ 0
|
|
1, // 1 ^ 0
|
|
1, // 0 ^ 1
|
|
0, // 1 ^ 1
|
|
};
|
|
|
|
// network net;
|
|
using network_type = cenet::nn<cenet::dense_input<2>,
|
|
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> xs;
|
|
xs[0][0] = static_cast<double>(i & 1);
|
|
xs[0][1] = static_cast<double>(i > 1);
|
|
|
|
xorNet.train(xs, s_trainData[i], EPSILON);
|
|
}
|
|
|
|
double acc = 0.0;
|
|
|
|
for (std::size_t i = 0; i < 4; ++i) {
|
|
cenet::mat<1, 2> xs;
|
|
xs[0][0] = static_cast<double>(i & 1);
|
|
xs[0][1] = static_cast<double>(i > 1);
|
|
|
|
double yHat = xorNet.feed(xs).get()[0][0];
|
|
double 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;
|
|
}
|