| 1 |
//--------------------------------------------------------------------- |
| 2 |
// name: mlp.ck |
| 3 |
// desc: training a multilayer perception (MLP), |
| 4 |
// a basic artificial neural network |
| 5 |
// (for a step-by-step example, see mlp-manual.ck) |
| 6 |
// |
| 7 |
// version: need chuck version 1.5.0.0 or higher |
| 8 |
// sorting: part of ChAI (ChucK for AI) |
| 9 |
// |
| 10 |
// uncomment for MLP API: |
| 11 |
// MLP.help(); |
| 12 |
// |
| 13 |
// author: Yikai Li |
| 14 |
// Ge Wang (https://ccrma.stanford.edu/~ge/) |
| 15 |
// date: Winter 2023 |
| 16 |
//--------------------------------------------------------------------- |
| 17 |
|
| 18 |
// instantiate a multilayer perception |
| 19 |
MLP mlp; |
| 20 |
// learning rate |
| 21 |
0.01 => float learningRate; |
| 22 |
// number of epochs |
| 23 |
100 => int epochs; |
| 24 |
|
| 25 |
// nodes per layer: input, [hidden layer(s)], output |
| 26 |
[3, 5, 5, 2] @=> int nodesPerLayer[]; |
| 27 |
|
| 28 |
// initialize with the units per layer with default activation function |
| 29 |
// default: AI.Sigmoid for all layers except output layer; |
| 30 |
// default: AI.Linear for output layer |
| 31 |
mlp.init( nodesPerLayer ); |
| 32 |
|
| 33 |
// (ALTERNATE #1) initialize with activation function |
| 34 |
// mlp.init( nodesPerLayer, AI.Sigmoid ); |
| 35 |
|
| 36 |
// (ALTERNATE #2) specify activation function per layer |
| 37 |
// [AI.ReLU, AI.Tanh, AI.Softmax] @=> int activationPerLayer[]; |
| 38 |
// (ALTERNATE #2) initialize with activation function per layer |
| 39 |
// mlp.init( nodesPerLayer, activationPerLayer ); |
| 40 |
|
| 41 |
// input observations |
| 42 |
[[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]] @=> float X[][]; |
| 43 |
// output observations |
| 44 |
[[0.1, 0.2], [0.3, 0.4]] @=> float Y[][]; |
| 45 |
// print |
| 46 |
<<< "training model...", "" >>>; |
| 47 |
// train the network |
| 48 |
mlp.train( X, Y, learningRate, epochs ); |
| 49 |
// ALTERNATE: train with default learning_rate=0.01, epochs=100 |
| 50 |
// mlp.train(X, Y); |
| 51 |
|
| 52 |
// save the network into a model file, which can loaded later |
| 53 |
// mlp.save( me.dir() + "model.txt" ); |
| 54 |
|
| 55 |
// predict given a new input |
| 56 |
[0.7, 0.8, 0.9] @=> float x[]; |
| 57 |
// array to how output |
| 58 |
float y[2]; |
| 59 |
// predict output given input |
| 60 |
mlp.predict(x, y); |
| 61 |
// print the output |
| 62 |
<<< "predicted output:", y[0], y[1] >>>; |