refactor: name the project "CeNet"

This commit is contained in:
2026-09-20 21:22:13 +02:00
parent 6156b919b8
commit 76eff9c837
6 changed files with 55 additions and 37 deletions
+208
View File
@@ -0,0 +1,208 @@
#include <algorithm>
#include <cassert>
#include <cenet/nn.hpp>
#include <cenet/tensor.hpp>
#include <chrono>
#include <fstream>
#include <iomanip>
#include <ios>
#include <iostream>
#include <iterator>
#include <limits>
#include <random>
#include <vector>
using network_type = cenet::nn<cenet::tensor_input<1, 28, 28>,
cenet::conv2d_layer<8, 3, 1, 1>,
cenet::relu_layer,
cenet::maxpool_layer<>,
cenet::conv2d_layer<16, 3, 1, 1>,
cenet::relu_layer,
cenet::maxpool_layer<>,
cenet::flatten_layer,
cenet::dense_layer<10>,
cenet::sigmoid_layer>;
static std::uniform_real_distribution<> dist(-1, 1);
struct data {
cenet::tensor<double, 1, 28, 28> xs;
cenet::mat<1, 10> ys;
};
using dataset = std::vector<data>;
template <std::size_t N, typename T>
static std::size_t col_largest_idx(const cenet::mat_col<N, T>& col) {
std::size_t maxIdx = 0;
std::remove_cv_t<T> max = col[0];
for (std::size_t i = 1; i < N; ++i) {
if (col[i] > max) {
max = col[i];
maxIdx = i;
}
}
return maxIdx;
}
static void read_be(std::uint32_t& value, std::ifstream& is) {
std::uint8_t bytes[sizeof(value)];
is.read(reinterpret_cast<char*>(bytes), sizeof(bytes));
value = bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3];
}
static dataset load_dataset(const char* labelsPath, const char* imagesPath) {
std::ifstream labels(labelsPath, std::ios::binary | std::ios::in);
std::ifstream images(imagesPath, std::ios::binary | std::ios::in);
if (!labels.is_open() || !images.is_open()) return {};
std::uint32_t magic = 0;
read_be(magic, labels);
if (magic != 0x801) return {};
read_be(magic, images);
if (magic != 0x803) return {};
dataset set;
std::uint32_t contentCount = 0;
read_be(contentCount, labels);
std::uint32_t contentCountCmp = 0;
read_be(contentCountCmp, images);
contentCount = std::min(contentCount, contentCountCmp);
set.resize(contentCount);
std::uint32_t dims[2];
read_be(dims[0], images);
read_be(dims[1], images);
assert(dims[0] == 28 && dims[1] == 28);
for (std::uint32_t i = 0; i < contentCount; ++i) {
for (std::uint32_t row = 0; row < dims[0]; ++row) {
for (std::uint32_t col = 0; col < dims[1]; ++col) {
std::uint8_t pixel = 0;
images.read(reinterpret_cast<char*>(&pixel), sizeof(pixel));
set[i].xs[0][row][col] = static_cast<double>(pixel) / 255.0;
}
}
std::uint8_t label = 0;
labels.read(reinterpret_cast<char*>(&label), sizeof(label));
set[i].ys[0][label] = 1.0;
}
std::cout << labelsPath << " and " << imagesPath << " successfully loaded!\n";
return set;
}
static void shuffle_dataset(dataset& set) {
static std::mt19937 s_rng(std::random_device{}());
std::shuffle(std::begin(set), std::end(set), s_rng);
}
int main(void) {
network_type* mnistNet = new network_type();
static constexpr const char* NETWORK_PATH = "./mnist-conv.nn";
std::ifstream file(NETWORK_PATH, std::ios::in | std::ios::binary);
if (file.is_open())
mnistNet->load_network(file);
else
mnistNet->fill_random(dist);
dataset trainSet = load_dataset("./mnist/train-labels-idx1-ubyte", "./mnist/train-images-idx3-ubyte");
if (trainSet.empty()) return 1;
dataset validationSet = load_dataset("./mnist/t10k-labels-idx1-ubyte", "./mnist/t10k-images-idx3-ubyte");
if (validationSet.empty()) return 1;
double bestLoss = std::numeric_limits<double>::max();
std::size_t patienceCounter = 0;
static constexpr std::size_t MAX_PATIENCE = 10;
static constexpr std::size_t MAX_EPOCHS = 1000;
static constexpr std::size_t BATCH_SIZE = 64;
static constexpr std::size_t EPL = 1; // Epochs Per Log
double learningRate = 0.001;
std::ofstream saveFile(NETWORK_PATH, std::ios::out | std::ios::binary);
network_type::learning_state* state = new network_type::learning_state();
for (std::size_t epoch = 0; epoch <= MAX_EPOCHS; ++epoch) {
shuffle_dataset(trainSet);
auto epochStart = std::chrono::high_resolution_clock::now();
for (std::size_t i = 0; i < trainSet.size(); i += BATCH_SIZE) {
if (i > 0) state->reset();
for (std::size_t j = 0; j < std::min(BATCH_SIZE, trainSet.size() - i); ++j)
mnistNet->backprop(trainSet[i + j].xs, trainSet[i + j].ys, *state);
mnistNet->apply(*state, learningRate);
}
auto trainEnd = std::chrono::high_resolution_clock::now();
double currentLoss = 0.0;
double currentAccuracy = 0.0;
{
double totalLoss = 0.0;
std::size_t hits = 0;
for (std::size_t i = 0; i < validationSet.size(); ++i) {
const auto& output = mnistNet->feed(validationSet[i].xs);
for (std::size_t j = 0; j < 10; ++j) {
double diff = output.get()[0][j] - validationSet[i].ys[0][j];
totalLoss += diff * diff;
}
if (col_largest_idx(output.get()[0]) == col_largest_idx(validationSet[i].ys[0])) ++hits;
}
currentLoss = totalLoss / static_cast<double>(validationSet.size());
currentAccuracy = (static_cast<double>(hits) / static_cast<double>(validationSet.size())) * 100.0;
}
auto epochEnd = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> trainTime = trainEnd - epochStart;
std::chrono::duration<double, std::milli> validationTime = epochEnd - trainEnd;
std::chrono::duration<double> epochTime = epochEnd - epochStart;
if ((epoch % EPL) == 0) {
std::cout << "Epoch " << epoch << " | Loss: " << currentLoss << " | Accuracy: " << currentAccuracy
<< " | Train: " << trainTime.count() << "ms | Validation: " << validationTime.count()
<< "ms | Total: " << std::fixed << std::setprecision(2) << epochTime.count() << "s\n";
}
if (currentLoss < bestLoss) {
bestLoss = currentLoss;
saveFile.seekp(0);
mnistNet->dump_network(saveFile);
patienceCounter = 0;
std::cout << "Network state saved at epoch " << epoch << '\n';
} else {
++patienceCounter;
}
if (patienceCounter >= MAX_PATIENCE) {
learningRate *= 0.5;
patienceCounter = 0;
std::cout << ">> Network plateaued. New learning rate: " << learningRate << '\n';
}
if (learningRate < 1e-6) {
std::cout << "Learning rate too small - hatling training.\n";
break;
}
}
return 0;
}
+88
View File
@@ -0,0 +1,88 @@
#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;
}