Brain.js 示例

Brain.js神经网络示例,包括前馈网络、循环网络和LSTM用于各种机器学习任务

💻 Brain.js 神经网络基础 javascript

🟢 simple ⭐⭐

Brain.js入门,创建和训练神经网络

⏱️ 20 min 🏷️ brainjs, neural network, machine learning
Prerequisites: Basic JavaScript, Neural network concepts
// Brain.js Neural Network Basics

// 1. Installation
// npm install brain.js or <script src="https://cdn.jsdelivr.net/npm/brain.js@latest/dist/brain.js.min.js"></script>

const brain = require('brain.js');

// 2. Simple XOR Problem with Feedforward Network
function xorExample() {
    console.log('=== XOR Problem with Feedforward Network ===');

    // Create a feedforward neural network
    const net = new brain.NeuralNetwork();

    // Training data for XOR
    const trainingData = [
        { input: [0, 0], output: [0] },
        { input: [0, 1], output: [1] },
        { input: [1, 0], output: [1] },
        { input: [1, 1], output: [0] }
    ];

    // Train the network
    net.train(trainingData, {
        iterations: 20000,
        log: true,
        logPeriod: 1000,
        errorThresh: 0.005
    });

    // Test the trained network
    console.log('Test Results:');
    console.log('XOR(0, 0):', net.run([0, 0])[0].toFixed(4));
    console.log('XOR(0, 1):', net.run([0, 1])[0].toFixed(4));
    console.log('XOR(1, 0):', net.run([1, 0])[0].toFixed(4));
    console.log('XOR(1, 1):', net.run([1, 1])[0].toFixed(4));

    return net;
}

// 3. Number Recognition
function numberRecognition() {
    console.log('\n=== Number Recognition ===');

    const net = new brain.NeuralNetwork();

    // Training data for recognizing handwritten-like patterns
    const trainingData = [
        // Pattern for 1
        { input: [0, 1, 0, 0, 1, 0, 0, 1, 0], output: [1] },
        // Pattern for 0
        { input: [1, 1, 1, 1, 0, 1, 1, 1, 1], output: [0] },
        // Pattern for 7
        { input: [1, 1, 1, 0, 0, 1, 0, 0, 1], output: [7] }
    ];

    net.train(trainingData);

    // Test with similar patterns
    const testPatterns = [
        [0, 1, 0, 0, 1, 0, 0, 1, 0], // Should be 1
        [1, 1, 1, 1, 0, 1, 1, 1, 1], // Should be 0
        [1, 1, 1, 0, 0, 1, 0, 0, 1]  // Should be 7
    ];

    testPatterns.forEach((pattern, i) => {
        const result = net.run(pattern);
        console.log(`Pattern ${i + 1}: ${result[0].toFixed(2)}`);
    });
}

// 4. Iris Flower Classification
function irisClassification() {
    console.log('\n=== Iris Flower Classification ===');

    const net = new brain.NeuralNetwork({
        hiddenLayers: [10],
        activation: 'sigmoid'
    });

    // Simplified Iris dataset (sepal length, sepal width, petal length, petal width)
    const trainingData = [
        // Setosa (output: [1, 0, 0])
        { input: [5.1, 3.5, 1.4, 0.2], output: [1, 0, 0] },
        { input: [4.9, 3.0, 1.4, 0.2], output: [1, 0, 0] },
        { input: [4.7, 3.2, 1.3, 0.2], output: [1, 0, 0] },

        // Versicolor (output: [0, 1, 0])
        { input: [7.0, 3.2, 4.7, 1.4], output: [0, 1, 0] },
        { input: [6.4, 3.2, 4.5, 1.5], output: [0, 1, 0] },
        { input: [6.9, 3.1, 4.9, 1.5], output: [0, 1, 0] },

        // Virginica (output: [0, 0, 1])
        { input: [6.3, 3.3, 6.0, 2.5], output: [0, 0, 1] },
        { input: [5.8, 2.7, 5.1, 1.9], output: [0, 0, 1] },
        { input: [7.1, 3.0, 5.9, 2.1], output: [0, 0, 1] }
    ];

    // Normalize input data to 0-1 range
    const normalizeInput = (input) => {
        return input.map(x => x / 10);
    };

    const normalizedData = trainingData.map(item => ({
        input: normalizeInput(item.input),
        output: item.output
    }));

    net.train(normalizedData, {
        iterations: 5000,
        errorThresh: 0.01,
        log: true,
        logPeriod: 1000
    });

    // Test the network
    const testData = [
        { input: [5.0, 3.6, 1.4, 0.2], actual: 'Setosa' }, // Should be Setosa
        { input: [6.7, 3.0, 5.2, 2.3], actual: 'Virginica' }, // Should be Virginica
        { input: [6.0, 2.9, 4.5, 1.5], actual: 'Versicolor' } // Should be Versicolor
    ];

    console.log('\nTest Results:');
    testData.forEach(test => {
        const result = net.run(normalizeInput(test.input));
        const maxIndex = result.indexOf(Math.max(...result));
        const species = ['Setosa', 'Versicolor', 'Virginica'][maxIndex];
        const confidence = Math.max(...result);

        console.log(`Actual: ${test.actual}, Predicted: ${species} (Confidence: ${(confidence * 100).toFixed(1)}%)`);
    });
}

// 5. Customer Churn Prediction
function customerChurnPrediction() {
    console.log('\n=== Customer Churn Prediction ===');

    const net = new brain.NeuralNetwork({
        hiddenLayers: [8, 4],
        activation: 'relu',
        learningRate: 0.01
    });

    // Features: [age, monthlyCharges, tenure, contractType, paymentMethod]
    // Output: [willChurn, willStay]
    const trainingData = [
        { input: [25, 50, 1, 0.2, 0.3], output: [1, 0] }, // Likely to churn
        { input: [45, 80, 24, 0.8, 0.7], output: [0, 1] }, // Likely to stay
        { input: [30, 60, 3, 0.1, 0.2], output: [1, 0] }, // Likely to churn
        { input: [50, 100, 60, 0.9, 0.8], output: [0, 1] }, // Likely to stay
        { input: [35, 70, 12, 0.3, 0.4], output: [0.6, 0.4] }, // Uncertain
        { input: [28, 40, 2, 0.1, 0.1], output: [0.9, 0.1] } // Very likely to churn
    ];

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

    // Test with new customers
    const testCustomers = [
        { name: 'John', features: [22, 45, 2, 0.2, 0.3] },
        { name: 'Sarah', features: [48, 90, 36, 0.7, 0.8] },
        { name: 'Mike', features: [31, 55, 6, 0.3, 0.3] }
    ];

    console.log('\nChurn Predictions:');
    testCustomers.forEach(customer => {
        const result = net.run(customer.features);
        const willChurn = result[0] > result[1];
        const confidence = Math.max(...result);

        console.log(`${customer.name}: ${willChurn ? 'Will Churn' : 'Will Stay'} (Confidence: ${(confidence * 100).toFixed(1)}%)`);
        console.log(`  Churn Probability: ${(result[0] * 100).toFixed(1)}%, Stay Probability: ${(result[1] * 100).toFixed(1)}%`);
    });
}

// 6. Simple House Price Prediction
function housePricePrediction() {
    console.log('\n=== House Price Prediction ===');

    const net = new brain.NeuralNetwork({
        hiddenLayers: [10, 5],
        activation: 'sigmoid'
    });

    // Features: [bedrooms, bathrooms, sqft, age, locationScore]
    // Output: [normalizedPrice]
    const trainingData = [
        { input: [2, 1, 800, 20, 0.3], output: [150000 / 500000] },
        { input: [3, 2, 1200, 15, 0.5], output: [250000 / 500000] },
        { input: [4, 2, 1600, 10, 0.7], output: [350000 / 500000] },
        { input: [5, 3, 2000, 5, 0.8], output: [450000 / 500000] },
        { input: [3, 2, 1400, 8, 0.6], output: [300000 / 500000] },
        { input: [2, 1, 900, 25, 0.4], output: [180000 / 500000] }
    ];

    net.train(trainingData, {
        iterations: 20000,
        errorThresh: 0.01,
        log: true,
        logPeriod: 5000
    });

    // Test predictions
    const testHouses = [
        { description: '3 bed, 2 bath, 1300 sqft, 12 years old', features: [3, 2, 1300, 12, 0.6] },
        { description: '4 bed, 3 bath, 1800 sqft, 7 years old', features: [4, 3, 1800, 7, 0.75] },
        { description: '2 bed, 1 bath, 750 sqft, 30 years old', features: [2, 1, 750, 30, 0.2] }
    ];

    console.log('\nPrice Predictions:');
    testHouses.forEach(house => {
        const result = net.run(house.features);
        const predictedPrice = result[0] * 500000;

        console.log(`${house.description}:`);
        console.log(`  Predicted Price: $${predictedPrice.toFixed(2)}`);
    });
}

// 7. Neural Network Utilities
class NetworkUtilities {
    static saveNetwork(net, filename) {
        const json = net.toJSON();
        const fs = require('fs');
        fs.writeFileSync(filename, JSON.stringify(json, null, 2));
        console.log(`Network saved to ${filename}`);
    }

    static loadNetwork(filename) {
        const fs = require('fs');
        const json = JSON.parse(fs.readFileSync(filename));
        const net = new brain.NeuralNetwork();
        net.fromJSON(json);
        console.log(`Network loaded from ${filename}`);
        return net;
    }

    static evaluateNetwork(net, testData) {
        let correct = 0;
        let total = testData.length;

        testData.forEach(test => {
            const output = net.run(test.input);
            const predictedIndex = output.indexOf(Math.max(...output));
            const actualIndex = test.output.indexOf(1);

            if (predictedIndex === actualIndex) {
                correct++;
            }
        });

        const accuracy = (correct / total) * 100;
        console.log(`Accuracy: ${accuracy.toFixed(2)}% (${correct}/${total})`);
        return accuracy;
    }

    static visualizeNetwork(net) {
        const layers = net.layers;
        console.log('Network Architecture:');

        layers.forEach((layer, i) => {
            console.log(`Layer ${i}: ${layer.size} neurons`);
        });

        console.log(`Total connections: ${net.connections.length}`);
        console.log(`Activation function: ${net.activation}`);
    }
}

// 8. Hyperparameter Tuning Example
function hyperparameterTuning() {
    console.log('\n=== Hyperparameter Tuning ===');

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

    const configs = [
        { hiddenLayers: [2], learningRate: 0.3, activation: 'sigmoid' },
        { hiddenLayers: [4], learningRate: 0.1, activation: 'relu' },
        { hiddenLayers: [3, 3], learningRate: 0.01, activation: 'sigmoid' },
        { hiddenLayers: [5], learningRate: 0.5, activation: 'tanh' }
    ];

    configs.forEach((config, i) => {
        console.log(`\nConfig ${i + 1}: ${JSON.stringify(config)}`);

        const net = new brain.NeuralNetwork(config);
        const stats = net.train(trainingData, {
            iterations: 5000,
            errorThresh: 0.01,
            log: false
        });

        console.log(`  Final Error: ${stats.error.toFixed(6)}`);
        console.log(`  Iterations: ${stats.iterations}`);

        // Test accuracy
        const results = trainingData.map(test => {
            const output = net.run(test.input);
            const predicted = Math.round(output[0]);
            return predicted === test.output[0];
        });

        const accuracy = (results.filter(Boolean).length / results.length) * 100;
        console.log(`  Accuracy: ${accuracy.toFixed(1)}%`);
    });
}

// Run all examples
function runAllExamples() {
    console.log('Brain.js Neural Network Examples\n');

    xorExample();
    numberRecognition();
    irisClassification();
    customerChurnPrediction();
    housePricePrediction();
    hyperparameterTuning();

    // Demonstrate utilities
    console.log('\n=== Network Utilities Demo ===');
    const net = xorExample();
    NetworkUtilities.visualizeNetwork(net);
}

// Export for module usage
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        xorExample,
        numberRecognition,
        irisClassification,
        customerChurnPrediction,
        housePricePrediction,
        NetworkUtilities,
        hyperparameterTuning
    };
}

// Run examples
runAllExamples();

💻 LSTM和循环神经网络 javascript

🟡 intermediate ⭐⭐⭐

使用LSTM网络进行时间序列预测和序列生成

⏱️ 25 min 🏷️ brainjs, lstm, time series, prediction
Prerequisites: Basic JavaScript, Recurrent neural networks
// LSTM and Recurrent Neural Networks with Brain.js

const brain = require('brain.js');

// 1. Time Series Prediction with LSTM
function stockPricePrediction() {
    console.log('=== Stock Price Prediction with LSTM ===');

    // Create LSTM network
    const net = new brain.recurrent.LSTM();

    // Training data - sequential stock prices
    const trainingData = [
        [100, 102, 101, 103, 105, 104, 106],
        [150, 152, 151, 153, 155, 154, 156],
        [200, 202, 201, 203, 205, 204, 206]
    ];

    // Train the network
    console.log('Training LSTM network...');
    net.train(trainingData, {
        iterations: 1500,
        errorThresh: 0.01,
        log: true,
        logPeriod: 100
    });

    // Test predictions
    console.log('\nPredictions:');
    const testSequence = [100, 102, 101, 103, 105];
    const prediction = net.run(testSequence);
    console.log(`Input: [${testSequence.join(', ')}]`);
    console.log(`Next 2 values: [${prediction.join(', ')}]`);

    return net;
}

// 2. Text Generation with LSTM
function textGeneration() {
    console.log('\n=== Text Generation with LSTM ===');

    const net = new brain.recurrent.LSTM();

    // Training text data
    const trainingTexts = [
        'hello world',
        'how are you',
        'nice to meet you',
        'good morning',
        'have a great day',
        'see you later',
        'thank you very much',
        'welcome to our team'
    ];

    // Train the network
    console.log('Training text generation...');
    net.train(trainingTexts, {
        iterations: 1500,
        errorThresh: 0.025,
        log: true,
        logPeriod: 100
    });

    // Generate text
    console.log('\nGenerated Text:');
    const prompts = ['hello', 'good', 'nice', 'thank'];

    prompts.forEach(prompt => {
        const generated = net.run(prompt);
        console.log(`Prompt: "${prompt}" -> Generated: "${generated}"`);
    });

    return net;
}

// 3. Music Pattern Generation
function musicPatternGeneration() {
    console.log('\n=== Music Pattern Generation ===');

    const net = new brain.recurrent.LSTM();

    // Training data - musical sequences (simplified representation)
    // Using numbers to represent notes: 0=C, 1=D, 2=E, 3=F, 4=G, 5=A, 6=B
    const trainingData = [
        [0, 2, 4, 2, 0],  // C-E-G-E-C (C major chord arpeggio)
        [1, 3, 5, 3, 1],  // D-F#-A-F#-D (D major)
        [2, 4, 6, 4, 2],  // E-G#-B-G#-E (E major)
        [0, 1, 2, 3, 4],  // C-D-E-F-G (C major scale)
        [4, 3, 2, 1, 0],  // G-F-E-D-C (descending scale)
        [0, 0, 4, 4, 0, 0, 4]  // C-C-G-G-C-C-G (simple rhythm)
    ];

    // Train the network
    console.log('Training music patterns...');
    net.train(trainingData, {
        iterations: 2000,
        errorThresh: 0.01,
        log: false
    });

    // Generate new patterns
    console.log('\nGenerated Music Patterns:');
    const seedPatterns = [
        [0, 2],    // Start with C-E
        [1, 3],    // Start with D-F#
        [0, 0, 4]  // Start with C-C-G
    ];

    seedPatterns.forEach((seed, i) => {
        const generated = net.run(seed);
        const notes = generated.map(note => ['C', 'D', 'E', 'F', 'G', 'A', 'B'][note] || '?');
        console.log(`Pattern ${i + 1}: Seed [${seed.join('-')}] -> Generated [${notes.join('-')}]`);
    });

    return net;
}

// 4. Weather Prediction
function weatherPrediction() {
    console.log('\n=== Weather Prediction ===');

    const net = new brain.recurrent.LSTM();

    // Weather data sequences [temperature, humidity, pressure]
    const trainingData = [
        [[20, 60, 1013], [22, 65, 1012], [24, 70, 1011], [23, 68, 1010]],
        [[15, 80, 1010], [16, 78, 1009], [18, 75, 1008], [17, 77, 1007]],
        [[25, 50, 1015], [26, 48, 1014], [24, 55, 1013], [23, 58, 1012]],
        [[10, 90, 1005], [12, 85, 1006], [14, 80, 1007], [13, 82, 1008]]
    ];

    // Train the network
    console.log('Training weather prediction model...');
    net.train(trainingData, {
        iterations: 1000,
        errorThresh: 0.02,
        log: false
    });

    // Predict next weather
    console.log('\nWeather Predictions:');
    const currentWeather = [[20, 60, 1013], [22, 65, 1012], [24, 70, 1011]];
    const prediction = net.run(currentWeather);

    console.log('Current weather sequence:');
    currentWeather.forEach((day, i) => {
        console.log(`Day ${i + 1}: Temp=${day[0]}°C, Humidity=${day[1]}%, Pressure=${day[2]} hPa`);
    });

    console.log('\nPredicted next day:');
    console.log(`Temp=${prediction[0].toFixed(1)}°C, Humidity=${prediction[1].toFixed(1)}%, Pressure=${prediction[2].toFixed(1)} hPa`);

    return net;
}

// 5. Sales Forecasting
function salesForecasting() {
    console.log('\n=== Sales Forecasting ===');

    const net = new brain.recurrent.LSTM();

    // Sales data sequences
    const trainingData = [
        [100, 120, 150, 180, 200, 220],  // Growing sales
        [300, 280, 260, 240, 220, 200],  // Declining sales
        [150, 160, 155, 165, 170, 175],  // Fluctuating sales
        [50, 60, 80, 100, 130, 160],     // Rapid growth
        [200, 190, 185, 195, 210, 205]   // Seasonal pattern
    ];

    // Train the network
    console.log('Training sales forecasting model...');
    net.train(trainingData, {
        iterations: 2000,
        errorThresh: 0.015,
        log: false
    });

    // Forecast future sales
    console.log('\nSales Forecasts:');
    const testSequences = [
        [100, 120, 150, 180],
        [300, 280, 260, 240],
        [50, 60, 80, 100]
    ];

    testSequences.forEach((sequence, i) => {
        const forecast = net.run(sequence);
        console.log(`Sequence ${i + 1}: [${sequence.join(', ')}] -> Forecast: [${forecast.join(', ')}]`);
    });

    return net;
}

// 6. Sentiment Analysis over Time
function temporalSentimentAnalysis() {
    console.log('\n=== Temporal Sentiment Analysis ===');

    const net = new brain.recurrent.LSTM();

    // Training data - sentiment sequences over time
    // 1=positive, 0=negative, 0.5=neutral
    const trainingData = [
        [1, 1, 1, 0.5, 1],      // Consistently positive
        [0, 0, 0, 0, 0.2],      // Consistently negative
        [0.5, 0.5, 1, 1, 0.8],   // Improving sentiment
        [1, 0.8, 0.5, 0.2, 0],   // Declining sentiment
        [0.5, 1, 0.5, 1, 0.5]    // Fluctuating sentiment
    ];

    // Train the network
    console.log('Training temporal sentiment model...');
    net.train(trainingData, {
        iterations: 1500,
        errorThresh: 0.01,
        log: false
    });

    // Predict sentiment trend
    console.log('\nSentiment Predictions:');
    const sentimentSequences = [
        [1, 1, 0.5],    // Started positive, went neutral
        [0, 0.2, 0.5],  // Started negative, improving
        [1, 0.8, 0.6]   // Positive but declining
    ];

    sentimentSequences.forEach((sequence, i) => {
        const prediction = net.run(sequence);
        const sentimentLabel = prediction > 0.6 ? 'Positive' : prediction < 0.4 ? 'Negative' : 'Neutral';
        console.log(`Sequence ${i + 1}: [${sequence.join(', ')}] -> Next: ${prediction.toFixed(3)} (${sentimentLabel})`);
    });

    return net;
}

// 7. Game AI - Simple Sequence Learning
function gameAISequences() {
    console.log('\n=== Game AI - Pattern Learning ===');

    const net = new brain.recurrent.LSTM();

    // Training data - game move sequences
    // 0=rock, 1=paper, 2=scissors
    const trainingData = [
        [0, 1, 2, 0, 1],      // Rock-Paper-Scissors pattern
        [2, 2, 1, 1, 0],      // Scissors-Scissors-Paper-Paper-Rock
        [0, 0, 1, 2, 2],      // Rock-Rock-Paper-Scissors-Scissors
        [1, 0, 1, 0, 1]       // Paper-Rock-Paper-Rock-Paper
    ];

    // Train the network
    console.log('Training game AI...');
    net.train(trainingData, {
        iterations: 1000,
        errorThresh: 0.01,
        log: false
    });

    // Predict next moves
    console.log('\nPredicted Game Moves:');
    const moveSequences = [
        [0, 1, 2],    // Rock-Paper-Scissors
        [1, 0, 1],    // Paper-Rock-Paper
        [2, 2, 1]     // Scissors-Scissors-Paper
    ];

    const moveNames = ['Rock', 'Paper', 'Scissors'];

    moveSequences.forEach((sequence, i) => {
        const prediction = net.run(sequence);
        const predictedMove = Math.round(prediction[0]);
        console.log(`Sequence ${i + 1}: [${sequence.map(m => moveNames[m]).join('-')}] -> Predicted: ${moveNames[predictedMove]}`);
    });

    return net;
}

// 8. Advanced LSTM Utilities
class LSTMUtilities {
    static createSequenceGenerator(net, maxLength = 10) {
        return function(seed, steps = 5) {
            const sequence = [...seed];
            let current = seed;

            for (let i = 0; i < steps; i++) {
                const next = net.run(current);
                sequence.push(...next);
                current = current.slice(1).concat(next);

                if (sequence.length >= maxLength) break;
            }

            return sequence.slice(seed.length);
        };
    }

    static evaluatePrediction(net, testData, tolerance = 0.1) {
        let totalError = 0;
        let totalPredictions = 0;

        testData.forEach(test => {
            const prediction = net.run(test.input);
            const expected = test.output;

            prediction.forEach((pred, i) => {
                if (expected[i] !== undefined) {
                    const error = Math.abs(pred - expected[i]);
                    totalError += error;
                    totalPredictions++;
                }
            });
        });

        const averageError = totalError / totalPredictions;
        const accuracy = Math.max(0, 100 - (averageError * 100));

        console.log(`Average Error: ${averageError.toFixed(4)}`);
        console.log(`Prediction Accuracy: ${accuracy.toFixed(2)}%`);

        return { averageError, accuracy };
    }

    static visualizeLearningCurve(trainingStats) {
        console.log('\nLearning Curve:');
        if (trainingStats && trainingStats.length > 0) {
            trainingStats.forEach((stat, i) => {
                const bar = '█'.repeat(Math.floor((1 - stat.error) * 20));
                console.log(`Epoch ${i + 1}: |${bar}| Error: ${stat.error.toFixed(4)}`);
            });
        }
    }
}

// 9. Transfer Learning with LSTM
function transferLearningExample() {
    console.log('\n=== Transfer Learning with LSTM ===');

    // Pre-train on general patterns
    const baseNet = new brain.recurrent.LSTM();
    const generalPatterns = [
        [1, 2, 3, 4, 5],
        [5, 4, 3, 2, 1],
        [1, 1, 2, 2, 3, 3]
    ];

    baseNet.train(generalPatterns, { iterations: 500 });

    console.log('Base model trained on general patterns');

    // Fine-tune on specific domain
    const specificData = [
        [10, 20, 30, 40, 50],  // Multiply by 10
        [50, 40, 30, 20, 10],  // Reverse
        [15, 15, 25, 25, 35, 35]  // Modified pattern
    ];

    // Continue training on specific data (transfer learning)
    baseNet.train(specificData, { iterations: 500 });

    console.log('Model fine-tuned on specific domain');

    // Test the transferred model
    const testInput = [10, 20, 30];
    const prediction = baseNet.run(testInput);
    console.log(`Transfer Learning Result: [${testInput}] -> [${prediction}]`);

    return baseNet;
}

// Run all LSTM examples
function runLSTMExamples() {
    console.log('Brain.js LSTM and Recurrent Network Examples\n');

    stockPricePrediction();
    textGeneration();
    musicPatternGeneration();
    weatherPrediction();
    salesForecasting();
    temporalSentimentAnalysis();
    gameAISequences();
    transferLearningExample();
}

// Export for module usage
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        stockPricePrediction,
        textGeneration,
        musicPatternGeneration,
        weatherPrediction,
        salesForecasting,
        temporalSentimentAnalysis,
        gameAISequences,
        LSTMUtilities,
        transferLearningExample
    };
}

// Run examples
runLSTMExamples();

💻 实际应用 javascript

🔴 complex ⭐⭐⭐⭐

实际应用包括推荐系统、异常检测和模式识别

⏱️ 35 min 🏷️ brainjs, applications, recommendation, anomaly
Prerequisites: Advanced JavaScript, Neural networks, ML concepts
// Practical Applications with Brain.js

const brain = require('brain.js');

// 1. Movie Recommendation System
class MovieRecommendationSystem {
    constructor() {
        this.net = new brain.NeuralNetwork({
            hiddenLayers: [20, 10],
            activation: 'relu'
        });
        this.movieGenres = ['Action', 'Comedy', 'Drama', 'Horror', 'Sci-Fi', 'Romance'];
        this.users = new Map();
    }

    // Add user ratings
    addUserRatings(userId, ratings) {
        // ratings: [{movieId, genre, rating, year}]
        this.users.set(userId, ratings);
    }

    // Prepare training data
    prepareTrainingData() {
        const trainingData = [];

        for (const [userId, ratings] of this.users) {
            // Group ratings by genre
            const genreRatings = new Map();

            ratings.forEach(rating => {
                if (!genreRatings.has(rating.genre)) {
                    genreRatings.set(rating.genre, []);
                }
                genreRatings.get(rating.genre).push(rating.rating);
            });

            // Calculate average rating per genre
            const avgRatings = new Array(this.movieGenres.length).fill(0);
            genreRatings.forEach((ratings, genre) => {
                const genreIndex = this.movieGenres.indexOf(genre);
                if (genreIndex !== -1) {
                    avgRatings[genreIndex] = ratings.reduce((a, b) => a + b, 0) / ratings.length;
                }
            });

            // Create training examples
            ratings.forEach(rating => {
                const input = [...avgRatings];
                input.push(rating.year / 2023); // Normalize year

                trainingData.push({
                    input: input,
                    output: [rating.rating / 5] // Normalize rating
                });
            });
        }

        return trainingData;
    }

    train() {
        const trainingData = this.prepareTrainingData();
        console.log(`Training recommendation system with ${trainingData.length} ratings...`);

        this.net.train(trainingData, {
            iterations: 5000,
            errorThresh: 0.01,
            log: true,
            logPeriod: 1000
        });
    }

    predictRating(userId, movieGenre, year) {
        const userRatings = this.users.get(userId);
        if (!userRatings) return null;

        // Calculate user's average genre preferences
        const genreRatings = new Map();
        userRatings.forEach(rating => {
            if (!genreRatings.has(rating.genre)) {
                genreRatings.set(rating.genre, []);
            }
            genreRatings.get(rating.genre).push(rating.rating);
        });

        const input = new Array(this.movieGenres.length).fill(0);
        genreRatings.forEach((ratings, genre) => {
            const genreIndex = this.movieGenres.indexOf(genre);
            if (genreIndex !== -1) {
                input[genreIndex] = ratings.reduce((a, b) => a + b, 0) / ratings.length;
            }
        });
        input.push(year / 2023);

        const output = this.net.run(input);
        return Math.round(output[0] * 5 * 10) / 10; // Round to 1 decimal place
    }

    getRecommendations(userId, candidateMovies) {
        const recommendations = [];

        candidateMovies.forEach(movie => {
            const predictedRating = this.predictRating(userId, movie.genre, movie.year);
            if (predictedRating) {
                recommendations.push({
                    ...movie,
                    predictedRating,
                    confidence: Math.abs(predictedRating - 2.5) / 2.5 // How confident we are
                });
            }
        });

        return recommendations
            .sort((a, b) => b.predictedRating - a.predictedRating)
            .slice(0, 10); // Top 10 recommendations
    }
}

// 2. Anomaly Detection System
class AnomalyDetectionSystem {
    constructor(featureCount) {
        this.net = new brain.NeuralNetwork({
            hiddenLayers: [featureCount * 2, featureCount],
            activation: 'tanh'
        });
        this.threshold = 0.1;
        this.normalData = [];
    }

    // Train on normal data
    trainNormal(normalData) {
        this.normalData = normalData;

        // Autoencoder setup: same input and output for normal data
        const trainingData = normalData.map(data => ({
            input: data,
            output: data
        }));

        console.log(`Training anomaly detector with ${trainingData.length} normal samples...`);

        this.net.train(trainingData, {
            iterations: 3000,
            errorThresh: 0.01,
            log: false
        });

        // Calculate reconstruction error threshold
        this.calculateThreshold(normalData);
    }

    calculateThreshold(data) {
        const errors = data.map(sample => {
            const output = this.net.run(sample);
            return this.calculateReconstructionError(sample, output);
        });

        const meanError = errors.reduce((a, b) => a + b, 0) / errors.length;
        const stdError = Math.sqrt(
            errors.reduce((sq, n) => sq + Math.pow(n - meanError, 2), 0) / errors.length
        );

        this.threshold = meanError + 2 * stdError; // 2 standard deviations
        console.log(`Anomaly threshold set to ${this.threshold.toFixed(4)}`);
    }

    calculateReconstructionError(input, output) {
        return Math.sqrt(
            input.reduce((sum, val, i) => sum + Math.pow(val - output[i], 2), 0)
        );
    }

    isAnomaly(dataPoint) {
        const output = this.net.run(dataPoint);
        const error = this.calculateReconstructionError(dataPoint, output);

        return {
            isAnomaly: error > this.threshold,
            error,
            threshold: this.threshold
        };
    }

    detectAnomalies(dataStream) {
        const anomalies = [];

        dataStream.forEach((dataPoint, index) => {
            const result = this.isAnomaly(dataPoint);
            if (result.isAnomaly) {
                anomalies.push({
                    index,
                    data: dataPoint,
                    error: result.error
                });
            }
        });

        return anomalies;
    }
}

// 3. Pattern Recognition for Handwritten Digits
class DigitRecognizer {
    constructor() {
        this.net = new brain.NeuralNetwork({
            hiddenLayers: [64, 32],
            activation: 'sigmoid'
        });
        this.imageSize = 28; // 28x28 pixels
    }

    // Convert image to normalized input array
    preprocessImage(imageData) {
        // Flatten and normalize image data (0-255 -> 0-1)
        return imageData.map(pixel => pixel / 255);
    }

    // Create one-hot encoded output
    createOneHot(digit) {
        const output = new Array(10).fill(0);
        output[digit] = 1;
        return output;
    }

    // Train on digit samples
    train(trainingData) {
        const processedData = trainingData.map(sample => ({
            input: this.preprocessImage(sample.image),
            output: this.createOneHot(sample.label)
        }));

        console.log(`Training digit recognizer with ${processedData.length} samples...`);

        this.net.train(processedData, {
            iterations: 10000,
            errorThresh: 0.01,
            log: true,
            logPeriod: 1000
        });
    }

    // Predict digit from image
    predict(imageData) {
        const input = this.preprocessImage(imageData);
        const output = this.net.run(input);

        const maxIndex = output.indexOf(Math.max(...output));
        const confidence = Math.max(...output);

        return {
            digit: maxIndex,
            confidence,
            probabilities: output.map((prob, i) => ({
                digit: i,
                probability: prob
            }))
        };
    }
}

// 4. Financial Risk Assessment
class RiskAssessmentSystem {
    constructor() {
        this.net = new brain.NeuralNetwork({
            hiddenLayers: [15, 8],
            activation: 'sigmoid'
        });
    }

    // Normalize features
    normalizeFeatures(features) {
        // Features: [age, income, creditScore, debtRatio, employmentYears]
        return [
            features[0] / 100,        // age (max 100)
            features[1] / 200000,     // income (max 200k)
            features[2] / 850,        // credit score (max 850)
            features[3],              // debt ratio (already 0-1)
            features[4] / 50          // employment years (max 50)
        ];
    }

    // Train with historical data
    train(historicalData) {
        const trainingData = historicalData.map(sample => ({
            input: this.normalizeFeatures(sample.features),
            output: [sample.riskScore] // 0=low, 1=high
        }));

        console.log(`Training risk assessment model with ${trainingData.length} samples...`);

        this.net.train(trainingData, {
            iterations: 8000,
            errorThresh: 0.01,
            log: false
        });
    }

    // Assess risk for new applicant
    assessRisk(applicant) {
        const input = this.normalizeFeatures(applicant);
        const output = this.net.run(input);
        const riskScore = output[0];

        let riskLevel;
        if (riskScore < 0.3) riskLevel = 'Low';
        else if (riskScore < 0.7) riskLevel = 'Medium';
        else riskLevel = 'High';

        return {
            riskScore: riskScore,
            riskLevel,
            recommendation: riskScore < 0.6 ? 'Approve' : 'Manual Review'
        };
    }
}

// 5. Sensor Data Predictor
class SensorPredictor {
    constructor(sensorCount) {
        this.net = new brain.recurrent.LSTM();
        this.sensorCount = sensorCount;
    }

    train(sensorData) {
        console.log(`Training sensor predictor with ${sensorData.length} readings...`);

        this.net.train(sensorData, {
            iterations: 2000,
            errorThresh: 0.02,
            log: false
        });
    }

    predictNext(readings, stepsAhead = 1) {
        if (readings.length < 2) return null;

        let currentSequence = readings.slice(-5); // Use last 5 readings
        const predictions = [];

        for (let i = 0; i < stepsAhead; i++) {
            const next = this.net.run(currentSequence);
            predictions.push(next);
            currentSequence = currentSequence.slice(1).concat([next]);
        }

        return predictions;
    }
}

// 6. Traffic Pattern Analysis
class TrafficAnalyzer {
    constructor() {
        this.net = new brain.NeuralNetwork({
            hiddenLayers: [20, 10],
            activation: 'relu'
        });
    }

    train(trafficData) {
        // Features: [hour, dayOfWeek, isHoliday, weather, temperature]
        // Output: [trafficLevel]
        const trainingData = trafficData.map(sample => ({
            input: [
                sample.hour / 24,
                sample.dayOfWeek / 7,
                sample.isHoliday ? 1 : 0,
                sample.weather / 5, // 0-5 scale
                sample.temperature / 50 // Normalized
            ],
            output: [sample.trafficLevel / 10] // 0-10 scale
        }));

        console.log(`Training traffic analyzer with ${trainingData.length} data points...`);

        this.net.train(trainingData, {
            iterations: 5000,
            errorThresh: 0.01,
            log: false
        });
    }

    predictTraffic(conditions) {
        const input = [
            conditions.hour / 24,
            conditions.dayOfWeek / 7,
            conditions.isHoliday ? 1 : 0,
            conditions.weather / 5,
            conditions.temperature / 50
        ];

        const output = this.net.run(input);
        const trafficLevel = Math.round(output[0] * 10);

        let congestion;
        if (trafficLevel < 3) congestion = 'Light';
        else if (trafficLevel < 7) congestion = 'Moderate';
        else congestion = 'Heavy';

        return {
            trafficLevel,
            congestion,
            recommendation: trafficLevel > 7 ? 'Avoid Peak Hours' : 'Normal Traffic'
        };
    }
}

// 7. Demo Functions
function demonstrateApplications() {
    console.log('Brain.js Practical Applications Demo\n');

    // Movie Recommendation Demo
    console.log('=== Movie Recommendation System ===');
    const movieRec = new MovieRecommendationSystem();

    // Add sample user data
    movieRec.addUserRatings('user1', [
        { movieId: 1, genre: 'Action', rating: 5, year: 2023 },
        { movieId: 2, genre: 'Sci-Fi', rating: 4, year: 2022 },
        { movieId: 3, genre: 'Action', rating: 3, year: 2021 },
        { movieId: 4, genre: 'Comedy', rating: 2, year: 2023 }
    ]);

    movieRec.addUserRatings('user2', [
        { movieId: 1, genre: 'Action', rating: 2, year: 2023 },
        { movieId: 2, genre: 'Comedy', rating: 5, year: 2022 },
        { movieId: 3, genre: 'Romance', rating: 4, year: 2021 },
        { movieId: 4, genre: 'Comedy', rating: 4, year: 2023 }
    ]);

    movieRec.train();

    const candidateMovies = [
        { id: 5, genre: 'Action', year: 2024, title: 'Action Hero 2024' },
        { id: 6, genre: 'Comedy', year: 2024, title: 'Funny Movie 2024' },
        { id: 7, genre: 'Sci-Fi', year: 2023, title: 'Space Adventure' }
    ];

    const recommendations = movieRec.getRecommendations('user1', candidateMovies);
    console.log('Recommendations for User 1:');
    recommendations.forEach((rec, i) => {
        console.log(`  ${i + 1}. ${rec.title} - Predicted Rating: ${rec.predictedRating}/5`);
    });

    // Anomaly Detection Demo
    console.log('\n=== Anomaly Detection System ===');
    const anomalyDetector = new AnomalyDetectionSystem(3);

    // Normal sensor readings
    const normalData = [
        [10.5, 20.3, 30.1],
        [10.6, 20.4, 30.2],
        [10.4, 20.2, 30.0],
        [10.7, 20.5, 30.3],
        [10.3, 20.1, 29.9]
    ];

    // Data stream with anomalies
    const dataStream = [
        [10.5, 20.3, 30.1], // Normal
        [10.6, 20.4, 30.2], // Normal
        [50.0, 80.0, 90.0], // Anomaly!
        [10.4, 20.2, 30.0], // Normal
        [10.7, 20.5, 30.3], // Normal
        [5.0, 100.0, 10.0]  // Anomaly!
    ];

    anomalyDetector.trainNormal(normalData);
    const anomalies = anomalyDetector.detectAnomalies(dataStream);

    console.log('Detected Anomalies:');
    anomalies.forEach(anomaly => {
        console.log(`  Index ${anomaly.index}: [${anomaly.data.join(', ')}] (Error: ${anomaly.error.toFixed(4)})`);
    });

    // Risk Assessment Demo
    console.log('\n=== Financial Risk Assessment ===');
    const riskAssessor = new RiskAssessmentSystem();

    // Historical data for training
    const historicalData = [
        { features: [25, 50000, 720, 0.3, 3], riskScore: 0.4 }, // Medium risk
        { features: [45, 80000, 750, 0.2, 10], riskScore: 0.2 }, // Low risk
        { features: [30, 30000, 600, 0.8, 1], riskScore: 0.8 }, // High risk
        { features: [35, 120000, 800, 0.1, 15], riskScore: 0.1 }, // Very low risk
        { features: [22, 25000, 550, 0.9, 0.5], riskScore: 0.9 } // Very high risk
    ];

    riskAssessor.train(historicalData);

    // Test new applicants
    const applicants = [
        { name: 'John Doe', features: [28, 60000, 700, 0.4, 5] },
        { name: 'Jane Smith', features: [40, 150000, 820, 0.1, 12] },
        { name: 'Mike Johnson', features: [26, 35000, 580, 0.7, 2] }
    ];

    console.log('Risk Assessment Results:');
    applicants.forEach(applicant => {
        const assessment = riskAssessor.assessRisk(applicant.features);
        console.log(`  ${applicant.name}: ${assessment.riskLevel} Risk (${assessment.recommendation})`);
    });
}

// Export classes and functions
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        MovieRecommendationSystem,
        AnomalyDetectionSystem,
        DigitRecognizer,
        RiskAssessmentSystem,
        SensorPredictor,
        TrafficAnalyzer,
        demonstrateApplications
    };
}

// Run the demonstration
demonstrateApplications();