#include #include #include #include "activation.h" #include "neuralnet_impl.h" #include "test.h" #include "test_util.h" #include TEST_CASE(neuralnet_train_xor_test) { const int num_layers = 2; const int layer_sizes[] = { 2, 2, 1 }; const nnActivation layer_activations[] = { nnRelu, nnIdentity }; nnNeuralNetwork* net = nnMakeNet(num_layers, layer_sizes, layer_activations); assert(net); // Train. #define N 4 const R inputs[N][2] = { { 0., 0. }, { 0., 1. }, { 1., 0. }, { 1., 1. } }; const R targets[N] = { 0., 1., 1., 0. }; nnMatrix inputs_matrix = nnMatrixMake(N, 2); nnMatrix targets_matrix = nnMatrixMake(N, 1); nnMatrixInit(&inputs_matrix, (const R*)inputs); nnMatrixInit(&targets_matrix, targets); nnTrainingParams params = { .learning_rate = 0.1, .max_iterations = 500, .seed = 0, .weight_init = nnWeightInit01, .debug = false, }; nnTrain(net, &inputs_matrix, &targets_matrix, ¶ms); // Test. #define M 4 nnQueryObject* query = nnMakeQueryObject(net, /*num_inputs=*/M); const R test_inputs[M][2] = { { 0., 0. }, { 1., 0. }, { 0., 1. }, { 1., 1. } }; nnMatrix test_inputs_matrix = nnMatrixMake(M, 2); nnMatrixInit(&test_inputs_matrix, (const R*)test_inputs); nnQuery(net, query, &test_inputs_matrix); const R expected_outputs[M] = { 0., 1., 1., 0. }; for (int i = 0; i < M; ++i) { const R test_output = nnMatrixAt(nnNetOutputs(query), i, 0); printf("\nInput: (%f, %f), Output: %f, Expected: %f\n", test_inputs[i][0], test_inputs[i][1], test_output, expected_outputs[i]); } for (int i = 0; i < M; ++i) { const R test_output = nnMatrixAt(nnNetOutputs(query), i, 0); TEST_TRUE(double_eq(test_output, expected_outputs[i], OUTPUT_EPS)); } nnDeleteQueryObject(&query); nnDeleteNet(&net); }