用于异或门的 Javascript 中的简单感知器 [英] Simple Perceptron In Javascript for XOR gate

查看:50
本文介绍了用于异或门的 Javascript 中的简单感知器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用单个感知器来预测 XOR 门.但是,结果似乎是完全随机的,我找不到错误.

I tried to use a single perceptron to predict the XOR gate. However, the results seem to be completely random and I cannot find the error.

我在这里做错了什么?- 我的训练方法错了吗?- 或者感知器模型中是否有任何错误?- 或者单个感知器不能用于这个问题?

What am I doing wrong here ? - Is my training method wrong? - or is there any error in the perceptron model ? - or a single perceptron cannot be used for this problem ?

class Perceptron {

    constructor(input_nodes, learning_rate) {
        this.nodes = input_nodes;
        this.bias = Math.random() * 2 - 1;
        this.learning_rate = learning_rate;
        this.weights = [];

        for (let i = 0; i < input_nodes; i++) {
            this.weights.push(Math.random() * 2 - 1)
        }
    }

    train (inputs, desired_output) {

        // Guess the result
        let guess = this.predict(inputs);
        let error = desired_output - guess;

        // Adjust weights and bias
        for (let i = 0; i < this.weights.length; i++) {
            this.weights[i] += this.learning_rate * error * inputs[i];         
        }
        this.bias += error * this.learning_rate;
    }

    predict (input_array) {

        if ( input_array.length != this.nodes) throw new Error({message: 'Invalid Input!'})

        let sum = this.bias;
        for (let i = 0; i < input_array.length; i++) {
            sum += this.weights[i] * input_array[i];
        }

        return this.activate(sum);
    }

    activate (num) {
        return num < 0 ? 0 : 1;
    }
}

module.exports = Perceptron;

if ( require.main === module ) {
    let p = new Perceptron(2, 0.003);

    for ( let i = 0; i < 1000; i++ ) {
        p.train([0, 0], 0);
        p.train([0, 1], 1);
        p.train([1, 0], 1);
        p.train([1, 1], 0);
    }

    console.log( p.predict([0, 1]) )
}

推荐答案

您似乎没有隐藏层.神经网络至少有一个中间"层,它也传播这些值.像这样

You don't seem to have a hidden layer. Neural Networks have at least one 'middle' layer that also propagates the values. like so

这里是制作简单神经网络的好地方.

Here is a great place to make a simple neural net.

这篇关于用于异或门的 Javascript 中的简单感知器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆