Perceptron - Simplest neural network

node v18.11.0
version: 1.0.1
endpointsharetweet
Medium article: https://medium.com/@waywardverities/making-a-perceptron-in-javascript-because-its-inefficient-a16ea21ce02c
const X_inputs = [ [0, 0], [0, 1], [1, 0], [1, 1] ] const y_outputs = [ 0, 1, 1, 1 ]
// Settings const epochs = 5 const learning_rate = 0.01 const log_epochs = false
let weights = [0, 0] let bias = 0 for (i = 0; i < epochs; i++) { if (log_epochs) console.log(`⏩ Epoch ${i}`) // Loop through each in/output every epoch for (j = 0; j < y_outputs.length; j++) { x = X_inputs[j] y_target = y_outputs[j] // Prediction can only be 0 or 1, error can be -1, 0 or 1 y_predicted = predict(x) error = y_target - y_predicted if (log_epochs) console.log(`${x} ⏩ Target y: ${y_target} ⏩ Predicted y: ${y_predicted} / error: ${error}`) // Update the weights and the bias weights = weights.map((weight, i) => { return weight += x[i] * error * learning_rate }) bias += learning_rate * error if (log_epochs) console.log(`Weights ${weights} / bias ${bias}`) } if (log_epochs) console.log(`After epoch: ${weights} - ${bias}`) } console.log(`Bias after ${bias}`) console.log(`Weights after ${weights}`) // Uses global weights and bias function predict(x) { const y_pred = x[0] * weights[0] + x[1] * weights[1] + bias if (y_pred >= 0) { return 1 } else { return 0 } }
console.log({weights, bias}) console.log([0,0], predict([0,0])) console.log([0,1], predict([0,1])) console.log([1,0], predict([1,0])) console.log([1,1], predict([1,1]))
Loading…

no comments

    sign in to comment