# Brain.js

> Source: https://learn-javascript.org/brain-js/
> Part of Learn JavaScript, free to read.

## Brain.js Tutorial

Brain.js is a GPU accelerated JavaScript library for Neural Networks. It's designed to be easy to use and understand, making it perfect for beginners to get started with neural networks.

### What You'll Learn

  - Basic neural network concepts and training

  - Different types of neural networks (feedforward, RNN, LSTM)

  - Practical applications: classification, pattern recognition, and text generation

  - Real-world projects and challenges

### Installation

You can include Brain.js in your project via a CDN:

```javascript
<script src="https://unpkg.com/brain.js"></script>
```

### 1. Understanding Neural Networks

Before diving into code, let's understand what neural networks do. They learn patterns from data and make predictions.

```javascript
<script>
function explainNeuralNetwork() {
  const explanation = `
    <h4>Neural Network Basics:</h4>
    <ul>
      <li><strong>Input Layer:</strong> Receives data (like [0, 1])</li>
      <li><strong>Hidden Layer(s):</strong> Process and learn patterns</li>
      <li><strong>Output Layer:</strong> Produces predictions (like [0.95])</li>
    </ul>
    <p><strong>Training Process:</strong></p>
    <ol>
      <li>Feed input data through the network</li>
      <li>Compare output with expected result</li>
      <li>Adjust weights to reduce error</li>
      <li>Repeat thousands of times</li>
    </ol>
  `;
  
  document.getElementById('explanation-output').innerHTML = explanation;
}

explainNeuralNetwork();
</script>
<div id="explanation-output"></div>
```

### 2. Hello World Example: XOR Function

Let's train a simple neural network to learn the XOR (exclusive OR) logical function.

```javascript
<script>
function trainXOR() {
  const net = new brain.NeuralNetwork({
    hiddenLayers: [3], // One hidden layer with 3 neurons
    activation: 'sigmoid'
  });

  // XOR truth table
  const trainingData = [
    { input: [0, 0], output: [0] },
    { input: [0, 1], output: [1] },
    { input: [1, 0], output: [1] },
    { input: [1, 1], output: [0] },
  ];

  const output = document.getElementById('xor-output');
  output.innerHTML = '<p>Training XOR network...</p>';

  // Train the network
  const stats = net.train(trainingData, {
    iterations: 2000,
    log: true,
    logPeriod: 500
  });

  // Test all combinations
  let results = '<h4>XOR Results:</h4><table border="1" style="border-collapse: collapse;">';
  results += '<tr><th>Input A</th><th>Input B</th><th>Expected</th><th>Predicted</th><th>Rounded</th></tr>';
  
  trainingData.forEach(data => {
    const result = net.run(data.input);
    const rounded = Math.round(result[0]);
    results += `<tr>
      <td>${data.input[0]}</td>
      <td>${data.input[1]}</td>
      <td>${data.output[0]}</td>
      <td>${result[0].toFixed(3)}</td>
      <td>${rounded}</td>
    </tr>`;
  });
  
  results += '</table>';
  results += `<p><strong>Training completed!</strong> Error: ${stats.error.toFixed(6)}, Iterations: ${stats.iterations}</p>`;
  
  output.innerHTML = results;
}

trainXOR();
</script>
<div id="xor-output"></div>
```

### 3. Pattern Recognition: Color Classification

Let's create a network that can classify colors as "warm" or "cool" based on RGB values.

```javascript
<script>
function colorClassification() {
  const net = new brain.NeuralNetwork({
    hiddenLayers: [6, 4]
  });

  // Training data: RGB values normalized to 0-1, classified as warm (1) or cool (0)
  const trainingData = [
    // Warm colors
    { input: [1, 0, 0], output: [1] },     // Red
    { input: [1, 0.5, 0], output: [1] },   // Orange
    { input: [1, 1, 0], output: [1] },     // Yellow
    { input: [1, 0, 1], output: [1] },     // Magenta
    { input: [0.5, 0, 0], output: [1] },   // Dark red
    
    // Cool colors
    { input: [0, 0, 1], output: [0] },     // Blue
    { input: [0, 1, 0], output: [0] },     // Green
    { input: [0, 1, 1], output: [0] },     // Cyan
    { input: [0.5, 0, 1], output: [0] },   // Purple
    { input: [0, 0.5, 0.5], output: [0] }, // Teal
  ];

  const output = document.getElementById('color-output');
  output.innerHTML = '<p>Training color classifier...</p>';

  net.train(trainingData, {
    iterations: 3000,
    errorThresh: 0.005
  });

  // Test with new colors
  const testColors = [
    { rgb: [0.8, 0.2, 0.1], name: 'Red-Orange' },
    { rgb: [0.1, 0.8, 0.2], name: 'Green' },
    { rgb: [0.2, 0.1, 0.9], name: 'Blue' },
    { rgb: [0.9, 0.7, 0.1], name: 'Yellow' },
    { rgb: [0.6, 0.1, 0.8], name: 'Purple' }
  ];

  let results = '<h4>Color Classification Results:</h4>';
  results += '<div style="display: flex; flex-wrap: wrap; gap: 10px;">';

  testColors.forEach(color => {
    const prediction = net.run(color.rgb)[0];
    const isWarm = prediction > 0.5;
    const confidence = isWarm ? (prediction * 100) : ((1 - prediction) * 100);
    const classification = isWarm ? 'Warm' : 'Cool';
    
    const rgbColor = `rgb(${Math.round(color.rgb[0] * 255)}, ${Math.round(color.rgb[1] * 255)}, ${Math.round(color.rgb[2] * 255)})`;
    
    results += `
      <div style="
        width: 120px; 
        height: 100px; 
        background-color: ${rgbColor}; 
        border: 2px solid #333; 
        display: flex; 
        flex-direction: column; 
        justify-content: center; 
        align-items: center; 
        color: white; 
        text-shadow: 1px 1px 1px black;
        font-size: 12px;
        text-align: center;
      ">
        <div>${color.name}</div>
        <div><strong>${classification}</strong></div>
        <div>${confidence.toFixed(1)}%</div>
      </div>
    `;
  });

  results += '</div>';
  output.innerHTML = results;
}

colorClassification();
</script>
<div id="color-output"></div>
```
