diff --git a/CMakeLists.txt b/CMakeLists.txt index 3018683..ed96a51 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,3 +6,6 @@ set(CMAKE_CXX_STANDARD 20) add_executable(xor src/xor.cpp) target_include_directories(xor PRIVATE include/) + +add_executable(mnist src/mnist.cpp) +target_include_directories(mnist PRIVATE include/) diff --git a/mnist.nn b/mnist.nn new file mode 100644 index 0000000..d448e49 Binary files /dev/null and b/mnist.nn differ diff --git a/src/mnist.cpp b/src/mnist.cpp new file mode 100644 index 0000000..743ee2e --- /dev/null +++ b/src/mnist.cpp @@ -0,0 +1,202 @@ +#include "mat.hpp" +#include "nn.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static std::uniform_real_distribution<> dist(-1, 1); + +struct data { + mat<1, 784> xs; + mat<1, 10> ys; +}; + +using dataset = std::vector; + +template +static std::size_t col_largest_idx(const mat_col& col) { + std::size_t maxIdx = 0; + std::remove_cv_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(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(&pixel), sizeof(pixel)); + + set[i].xs[0][(row * dims[0]) + col] = static_cast(pixel) / 255.0; + } + } + + std::uint8_t label = 0; + labels.read(reinterpret_cast(&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::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(validationSet.size()); + currentAccuracy = (static_cast(hits) / static_cast(validationSet.size())) * 100.0; + } + + auto epochEnd = std::chrono::high_resolution_clock::now(); + + std::chrono::duration trainTime = trainEnd - epochStart; + std::chrono::duration validationTime = epochEnd - trainEnd; + std::chrono::duration 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; +}