aboutsummaryrefslogtreecommitdiff
path: root/src/lib/test/train_linear_perceptron_non_origin_test.c
blob: 40a42e099d9fc4477042bfaf0c651593c9359d88 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <neuralnet/train.h>

#include "neuralnet_impl.h"
#include <neuralnet/matrix.h>
#include <neuralnet/neuralnet.h>

#include "test.h"
#include "test_util.h"

#include <assert.h>

TEST_CASE(neuralnet_train_linear_perceptron_non_origin_test) {
  const int     num_layers = 1;
  const int     input_size = 1;
  const nnLayer layers[]   = {
      {.type = nnLinear, .linear = {.input_size = 1, .output_size = 1}}
  };

  nnNeuralNetwork* net = nnMakeNet(layers, num_layers, input_size);
  assert(net);

// Train.

// Try to learn the Y = 2X + 1 line.
#define N 2
  const R inputs[N]  = {0., 1.};
  const R targets[N] = {1., 3.};

  nnMatrix inputs_matrix  = nnMatrixMake(N, 1);
  nnMatrix targets_matrix = nnMatrixMake(N, 1);
  nnMatrixInit(&inputs_matrix, inputs);
  nnMatrixInit(&targets_matrix, targets);

  nnTrainingParams params = {
      .learning_rate  = 0.7,
      .max_iterations = 20,
      .seed           = 0,
      .weight_init    = nnWeightInit01,
      .debug          = false,
  };

  nnTrain(net, &inputs_matrix, &targets_matrix, &params);

  const R weight          = nnMatrixAt(&net->layers[0].linear.weights, 0, 0);
  const R expected_weight = 2.0;
  printf(
      "\nTrained network weight: %f, Expected: %f\n", weight, expected_weight);
  TEST_TRUE(double_eq(weight, expected_weight, WEIGHT_EPS));

  const R bias          = nnMatrixAt(&net->layers[0].linear.biases, 0, 0);
  const R expected_bias = 1.0;
  printf("Trained network bias: %f, Expected: %f\n", bias, expected_bias);
  TEST_TRUE(double_eq(bias, expected_bias, WEIGHT_EPS));

  // Test.

  nnQueryObject* query = nnMakeQueryObject(net, 1);

  const R test_input[] = {2.3};
  R       test_output[1];
  nnQueryArray(net, query, test_input, test_output);

  const R expected_output = test_input[0] * expected_weight + expected_bias;
  printf("Output: %f, Expected: %f\n", test_output[0], expected_output);
  TEST_TRUE(double_eq(test_output[0], expected_output, OUTPUT_EPS));

  nnDeleteQueryObject(&query);
  nnDeleteNet(&net);
}