From 8f4856f9b166690a430deed4c8790f6aedc85b68 Mon Sep 17 00:00:00 2001 From: Engine Feeder Date: Sat, 10 Mar 2018 16:56:38 +0100 Subject: [PATCH] Fixed (de)serialization to include activation function. This fixes #96 by using a `replacer` on serialization to preserve the activation function as a string. On deserialization the function string is `eval()`-ed. This is dangerous as malicious code could be executed. Might be possible to port this to using `new Function()` instead. --- lib/nn.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/nn.js b/lib/nn.js index 0260280..a58ed4c 100644 --- a/lib/nn.js +++ b/lib/nn.js @@ -5,6 +5,13 @@ class ActivationFunction { this.func = func; this.dfunc = dfunc; } + + static deserialize(data) { + if (typeof data == 'string') { + data = JSON.parse(data); + } + return new ActivationFunction(eval(data.func), eval(data.dfunc)); + } } let sigmoid = new ActivationFunction( @@ -139,7 +146,7 @@ class NeuralNetwork { } serialize() { - return JSON.stringify(this); + return JSON.stringify(this, (k, v) => typeof v == 'function' ? v.toString() : v); } static deserialize(data) { @@ -152,6 +159,7 @@ class NeuralNetwork { nn.bias_h = Matrix.deserialize(data.bias_h); nn.bias_o = Matrix.deserialize(data.bias_o); nn.learning_rate = data.learning_rate; + nn.activation_function = ActivationFunction.deserialize(data.activation_function); return nn; }