| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <!DOCTYPE html>
- <html>
- <head>
- <title>Brain JS - LSTM Math</title>
- <meta charset="utf-8" />
- <meta http-equiv="Content-Type"
- content="text/html; charset=utf-8" />
- <meta name="viewport"
- content="width=device-width, initial-scale=1.0">
- <style>
- #network {
- background: #ccc;
- border: 1px solid red;
- width: 640px;
- height: 480px;
- }
- </style>
- <link rel="stylesheet" href="simple.min.css">
- </head>
- <body>
- <h1>Brain JS - LSTM Math</h1>
- <p>
- In this case, we test the math adding calcuation by LSTM model.
- </p>
- <h2>Test results</h2>
- <div id="input">
- <p>Input a math problem, like "1+2=" or "9+7=" in the below input box.</p>
- <input type="text"
- id="problem"></input>
- <button id="calcuate">Calculate</button>
- <button id="testall">Test all once</button>
- </div>
- <div id="output"></div>
- <h2>Network</h2>
- <div id="network"></div>
- </body>
- <script src="brain-browser.js"></script>
- <script type="text/javascript">
- const svg_config = {
- height: 480,
- width: 640,
- radius: 10,
- };
- // create a simple recurrent neural network
- const net = new brain.recurrent.LSTM();
- // used to build list below
- const mathProblemsSet = new Set();
- for (let i = 0; i < 10; i++) {
- for (let j = 0; j < 10; j++) {
- mathProblemsSet.add(`${i}+${j}=${i + j}`);
- mathProblemsSet.add(`${j}+${i}=${i + j}`);
- }
- }
- const mathProblems = Array.from(mathProblemsSet);
- console.log(mathProblems);
- net.train(mathProblems, { log: true, errorThresh: 0.03 });
- let errors = 0;
- document.getElementById("calcuate").onclick = () => {
- const input = document.getElementById("problem").value;
- const output = net.run(input)
- const predictedMathProblem = input + output;
- const error = mathProblems.indexOf(predictedMathProblem) <= -1 ? 1 : 0;
- errors += error;
- document.getElementById("output").innerHTML =
- `Output :${input}${output}` +
- `<br/>${error?'Error':'Correct'}, total error ${errors}`;
- };
- // Batch test for all problems
- document.getElementById("testall").onclick = () => {
- let results = 'Test all items:<br/><ul>';
- for (let i = 0; i < mathProblems.length; i++) {
- const input = mathProblems[i].split('=')[0] + '=';
- const output = net.run(input);
- const predictedMathProblem = input + output;
- const error = mathProblems.indexOf(predictedMathProblem) <= -1 ? 1 : 0;
- errors += error;
- results += '<li>';
- results += input + output;
- results += error ? ' - error' : '';
- results += '</li>';
- }
- results +='</ul>';
- results = `Batch test with ${errors} errors <br/>`+ results;
- document.getElementById("output").innerHTML = results;
- };
- document.getElementById("network").innerHTML = brain.utilities.toSVG(
- net,
- svg_config
- );
- </script>
- </html>
|