Skip to content

Commit

Permalink
Fixed (de)serialization to include activation function.
Browse files Browse the repository at this point in the history
This fixes CodingTrain#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.
  • Loading branch information
enginefeeder101 committed Mar 10, 2018
1 parent 846a259 commit 8f4856f
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/nn.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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) {
Expand All @@ -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;
}

Expand Down

0 comments on commit 8f4856f

Please sign in to comment.