feat: add mnist example
This commit is contained in:
+202
@@ -0,0 +1,202 @@
|
||||
#include "mat.hpp"
|
||||
#include "nn.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <ios>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
static std::uniform_real_distribution<> dist(-1, 1);
|
||||
|
||||
struct data {
|
||||
mat<1, 784> xs;
|
||||
mat<1, 10> ys;
|
||||
};
|
||||
|
||||
using dataset = std::vector<data>;
|
||||
|
||||
template <std::size_t N, typename T>
|
||||
static std::size_t col_largest_idx(const 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 * dims[0]) + 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) {
|
||||
auto rng = std::default_random_engine{};
|
||||
std::shuffle(std::begin(set), std::end(set), rng);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
using network_type = nn<784, 300, 100, 10>;
|
||||
network_type* mnistNet = new network_type();
|
||||
|
||||
static constexpr const char* NETWORK_PATH = "./mnist.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 = 5; // 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[0][j] - validationSet[i].ys[0][j];
|
||||
totalLoss += diff * diff;
|
||||
}
|
||||
|
||||
if (col_largest_idx(output[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;
|
||||
}
|
||||
}
|
||||
|
||||
saveFile.seekp(0);
|
||||
mnistNet->dump_network(saveFile);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user