summaryrefslogtreecommitdiffstats
path: root/example1.py
blob: 6620480acd2e4e5333b3be8373f7e02ae0e0629b (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#!/usr/bin/env python3
"""
# -*- coding: utf-8 -*-
#
# Copyright 2021 Michael Büsch <m@bues.ch>
#
# Licensed under the Apache License version 2.0
# or the MIT license, at your option.
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
"""

import mlplib as mlp
import numpy as np

def make_y(x):
    """Generate the true net output corresponding to the net input layer X.
    """
    def classify(x):
        if x <= 100.0:
            return np.array([1.0, 0.0, 0.0])
        elif x <= 500.0:
            return np.array([0.0, 1.0, 0.0])
        elif x <= 1000.0:
            return np.array([0.0, 0.0, 1.0])
        else:
            return np.array([0.0, 0.0, 0.0])
    nr_samples = x.shape[0]
    y = np.zeros((nr_samples, 3))
    for i in range(nr_samples):
        y[i] = classify(x[i, 0])
    return y

def make_x(nr_samples, nr_inputs):
    """Generate random net input data.
    """
    return mlp.random((nr_samples, nr_inputs)) * 1000.0

def make_net():
    """Construct the MLP network architecture.
    """
    nr_inputs = 1   # Number of inputs.
    layout = (6,    # First hidden layer size.
              12,   # Second hidden layer size.
              6,    # Third hidden layer size.
              3,)   # Output layer size.
    params = mlp.Parameters(
        weights=mlp.init_layers_weights(nr_inputs, layout), # Random weights init.
        biases=mlp.init_layers_biases(layout),              # Neutral bias init.
        actvns=(
            mlp.Sigmoid(),  # First hidden layer activation.
            mlp.Sigmoid(),  # Second hidden layer activation.
            mlp.Sigmoid(),  # Third hidden layer activation.
            mlp.Sigmoid(),  # Output layer activation.
            #mlp.Softmax(),  # Output layer activation.
        ),
    )
    return params

def train_net(params, show_progress):
    print("Synthesizing training data...")
    train_x = make_x(nr_samples=100000,
                     nr_inputs=params.nr_inputs)
    train_y = make_y(train_x)

    print("Synthesizing dev/test data...")
    test_x = make_x(nr_samples=100,
                    nr_inputs=params.nr_inputs)
    test_y = make_y(test_x)

    print("Training the network...")
    nr_iterations = 200
    minibatch_size = 128
    optimizer = mlp.AlphaDecaySimple(
        mlp.Adam(params, alpha=0.001, beta1=0.9, beta2=0.999),
        decay_rate=0.01)
    lossfn = mlp.MSE()
    train_loss = []
    for i in range(nr_iterations):
        show_progress(i, train_loss)
        for tx, ty in mlp.minibatches(train_x, train_y, minibatch_size):
            gradients, yh = mlp.backward_prop(tx, ty, params, lossfn)
            train_loss.append(lossfn.fn(yh, ty))
            optimizer.apply(i, gradients)

    train_yh = mlp.forward_prop(train_x, params)
    test_yh = mlp.forward_prop(test_x, params)
    test_loss = lossfn.fn(test_yh, test_y)

    # Calculate the percentage of matches in the test set.
    print("X", test_x)
    print("YH", mlp.collapse_bool_nodes(test_yh))
    print("Y", mlp.collapse_bool_nodes(test_y))
    train_match = mlp.proportion_equal(mlp.collapse_bool_nodes(train_yh),
                                       mlp.collapse_bool_nodes(train_y))
    test_match = mlp.proportion_equal(mlp.collapse_bool_nodes(test_yh),
                                      mlp.collapse_bool_nodes(test_y))

    print(params)
    print(f"Train set loss:  {train_loss[-1]:.6f}")
    print(f"Train set match: {train_match*100.0:.2f} %")
    print(f"Test set loss:   {test_loss:.6f}")
    print(f"Test set match:  {test_match*100.0:.2f} %")

    return train_loss

def example():
    mlp.seed(142)

    import matplotlib.pyplot as plt
    plt.ion()
    fig, ax = plt.subplots(1)
    fig.tight_layout()
    ax.set_title("Loss during training (live view...)")

    def show_progress(i, loss_values):
        if i % 4 == 0:
            print(f"Training epoch {i}...")
            ax.clear()
            ax.plot(loss_values)
            plt.pause(0.01)

    params = make_net()
    loss_values = train_net(params, show_progress)

    #TODO use plt.pause?
    #TODO scatterplot

    plt.ioff()
    ax.set_title("Loss during training")
    plt.show()

if __name__ == "__main__":
    example()

# vim: ts=4 sw=4 expandtab
bues.ch cgit interface