javascriptbrain.js

BrainJS ReferenceError: brain is not defined


I'm following a tutorial on how to work with neural networks with brain.js when I try to run the code it gives me a ReferenceError: brain is not defined i already installed via npm and have the CDN on the HTML.

const net = new brain.NeuralNetwork({ hiddenLayers: [3] });

const trainingData = [
  { input: [0, 0], output: [0] },
  { input: [0, 1], output: [1] },
  { input: [1, 0], output: [1] },
  { input: [1, 1], output: [0] }
];

net.train(trainingData);

console.log(net.run([0, 0]));

here´s the index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="//unpkg.com/brain.js"></script>

    <script src="index.js"></script>

</head>
<body>

</body>
</html>
````

Solution

  • Try adding the explicit protocol https:// rather than just using //. When I do this, your code works for me.

    const net = new brain.NeuralNetwork({ hiddenLayers: [3] });
    
    const trainingData = [
      { input: [0, 0], output: [0] },
      { input: [0, 1], output: [1] },
      { input: [1, 0], output: [1] },
      { input: [1, 1], output: [0] }
    ];
    
    net.train(trainingData);
    
    console.log(net.run([0, 0]));
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <script src="https://unpkg.com/brain.js"></script>
    
        <script src="index.js"></script>
    
    </head>
    <body>
    
    </body>
    </html>