NoJobEngine 2.0.7
Loading...
Searching...
No Matches
NeuralTests.cpp
Go to the documentation of this file.
1#include "NeuralNetwork.h"
2#include <cassert>
3#include <cmath>
4#include <iostream>
5#include <filesystem>
6using namespace NoJob::Neural;
7int main(){
8 Matrix a(2,2);a(0,0)=1;a(0,1)=2;a(1,0)=3;a(1,1)=4;auto b=Matrix::Multiply(a,a);assert(b(0,0)==7&&b(1,1)==22);
10 const std::vector<std::vector<float>> xs={{0,0},{0,1},{1,0},{1,1}},ys={{0},{1},{1},{0}};
11 float before=n.MeanSquaredError(xs,ys);TrainingOptions o;o.epochs=3000;o.batchSize=4;o.learningRate=.04f;o.adam=true;auto history=n.Train(xs,ys,o);float after=n.MeanSquaredError(xs,ys);
12 std::cout<<"XOR MSE "<<before<<" -> "<<after<<"\n";assert(after<0.02f);assert(history.epochLoss.size()==o.epochs);
13 auto path=(std::filesystem::temp_directory_path()/"nojob_neural_test.njn").string();n.Save(path);auto loaded=NeuralNetwork::Load(path);for(auto&x:xs)assert(std::abs(n.Predict(x)[0]-loaded.Predict(x)[0])<1e-6f);std::filesystem::remove(path);
14 bool rejected=false;try{n.Predict({1});}catch(const std::invalid_argument&){rejected=true;}assert(rejected);
15 std::cout<<"ALL NEURAL TESTS PASSED\n";
16}
Dense neural network inference, training and serialization.
int main()
static Matrix Multiply(const Matrix &a, const Matrix &b)
CPU-based feed-forward neural network with native C++ training.
static NeuralNetwork Load(const std::string &path)
Loads a serialized network.
void Save(const std::string &path) const
Serializes the network to a model asset.
std::vector< float > Predict(const std::vector< float > &input) const
Evaluates the network without changing its parameters.
void AddDense(size_t inputs, size_t outputs, Activation activation)
Appends a dense layer to the network.
float MeanSquaredError(const std::vector< std::vector< float > > &inputs, const std::vector< std::vector< float > > &targets) const
TrainingHistory Train(const std::vector< std::vector< float > > &inputs, const std::vector< std::vector< float > > &targets, const TrainingOptions &options={}, const std::function< bool(size_t, float)> &onEpoch={})
Trains on paired input and target samples.
Parameters controlling supervised neural network optimization.