添加自定义损失函数和 R/W 状态矩阵
// Create a new 神经网络. const net = new NeuralNetwork();
// Fabricate some training data. const trainingData = [ [0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0] ].map(v => ({ input: v.slice(0, 2), output: v.slice(2) }) );
// A custom loss function designed to train for XOR calculations.
// This function is so effective that you could actually train on
// random input data (Math.random() as input data, for example)
// and the 神经网络 would still come to the correct conclusion
// with little (if any) difference in training times.
function loss(actual, expected, inputs, ram) {
// Calculate the base loss. This is just a normal loss function so far.
const loss = expected - actual;
// Reward positive behavior by providing lower error values if the 神经网络 predicts the calculation correctly.
if (Math.round(actual) !== Math.round(inputs[0]) ^ Math.round(inputs[1]) loss *= 20;
// Return the calculated loss.
return loss;
}
// Define the training options. const trainOptions = { errorThresh: 0.011, iterations: 15000, loss };
// Train the 神经网络 using the custom loss function. net.train(trainingData, trainOptions);
// Calculate a ^ b function xor(a, b) { return Math.round(net.run([a, b])[0]); }
// Try it out! console.log(xor(0, 0)); console.log(xor(0, 1)); console.log(xor(1, 0)); console.log(xor(1, 1));
The `updateMemory` function is easy to implement as well. Here's a silly example that just randomizes the R/W state matrix:内容来源: BrainJS/brain.js