feat: add layers for CNNs

This commit is contained in:
2026-09-20 21:08:33 +02:00
parent 5bb278c9de
commit 27b1a677d9
7 changed files with 607 additions and 22 deletions
+19 -18
View File
@@ -1,5 +1,6 @@
#include "mat.hpp"
#include "nn.hpp"
#include "tensor.hpp"
#include <algorithm>
#include <cassert>
@@ -13,11 +14,22 @@
#include <random>
#include <vector>
using network_type = nn<tensor_input<1, 28, 28>,
conv2d_layer<8, 3, 1, 1>,
relu_layer,
maxpool_layer<>,
conv2d_layer<16, 3, 1, 1>,
relu_layer,
maxpool_layer<>,
flatten_layer,
dense_layer<10>,
sigmoid_layer>;
static std::uniform_real_distribution<> dist(-1, 1);
struct data {
mat<1, 784> xs;
mat<1, 10> ys;
tensor<double, 1, 28, 28> xs;
mat<1, 10> ys;
};
using dataset = std::vector<data>;
@@ -72,7 +84,7 @@ static dataset load_dataset(const char* labelsPath, const char* imagesPath) {
std::uint8_t pixel = 0;
images.read(reinterpret_cast<char*>(&pixel), sizeof(pixel));
set[i].xs[0][(row * dims[0]) + col] = static_cast<double>(pixel) / 255.0;
set[i].xs[0][row][col] = static_cast<double>(pixel) / 255.0;
}
}
@@ -87,22 +99,14 @@ static dataset load_dataset(const char* labelsPath, const char* imagesPath) {
}
static void shuffle_dataset(dataset& set) {
auto rng = std::default_random_engine{};
std::shuffle(std::begin(set), std::end(set), rng);
static std::mt19937 s_rng(std::random_device{}());
std::shuffle(std::begin(set), std::end(set), s_rng);
}
int main(void) {
using network_type = nn<dense_input<784>,
dense_layer<300>,
sigmoid_layer,
dense_layer<100>,
sigmoid_layer,
dense_layer<10>,
sigmoid_layer>;
network_type* mnistNet = new network_type();
static constexpr const char* NETWORK_PATH = "./mnist.nn";
static constexpr const char* NETWORK_PATH = "./mnist-conv.nn";
std::ifstream file(NETWORK_PATH, std::ios::in | std::ios::binary);
if (file.is_open())
@@ -123,7 +127,7 @@ int main(void) {
static constexpr std::size_t MAX_EPOCHS = 1000;
static constexpr std::size_t BATCH_SIZE = 64;
static constexpr std::size_t EPL = 5; // Epochs Per Log
static constexpr std::size_t EPL = 1; // Epochs Per Log
double learningRate = 0.001;
@@ -202,8 +206,5 @@ int main(void) {
}
}
saveFile.seekp(0);
mnistNet->dump_network(saveFile);
return 0;
}