How to train a tfjs model on logic gates

Using tensorflow for JavaScript to train an artificial intelligence model to effectively evaluate and predict expected output of a logic gate given two inputs.
training data is sourced from a two dimentional array truth table
// logic truth table
// -----------------
const truthTable = [
    [
        [[[0, 0], [0, 1], [1, 1], [1, 1]],
        [[0], [1], [1], [1]]]
    ]
];
The first pairs of numbers are the input proceeded by the output

import * as tf from '@tensorflow/tfjs'
// logic truth table
// -----------------
const logic = [
[
[
[
[0, 0],
[0, 1],
[1, 1],
[1, 1]
],
[
[0],
[1],
[1],
[1]
]
]
]
]
// tabulate logic gate
// ----------------------------------------
// ┌──────────────────────┐
// │ (index) | 0 | 1 | (values) |
// ├──────────────────────┤
// │ 0 | 0 | 0 | 0 |
// │ 1 | 0 | 1 | 1 |
// │ 2 | 1 | 0 | 1 |
// │ 3 | 1 | 1 | 1 |
// └──────────────────────┘
// Artificial intelligence model
// first layer has 2 inputs
// hidden layer has 4 input and 1 output
const model = tf.sequential()
model.add(tf.layers.dense({
inputShape: [2],
activation: 'sigmoid',
units: 4
}))
model.add(tf.layers.dense({
inputShape: [4],
activation: 'sigmoid',
units: 1
}))
model.compile({
loss: 'meanSquaredError',
optimizer: tf.train.adam(0.1)
})
// it's a function used train a model
function fit(input) {
return new Promise((resolve) => {
var train = model.fit(tf.tensor2d(input[0]), tf.tensor2d(input[1]), {
epochs: 500
})
train.then(() => {
// -----------
console.table(input[0])
console.table(input[1])
console.table(input[0][1])
// -------------
return new Promise((resolve) => {
const prediction = model.predict(tf.tensor2d([input[0][1]]))
const predictionPromise = prediction.data()
predictionPromise.then((output) => {
console.table(Object.entries(output))
})
})
})
})
}
fit(logic[0][0])
view raw tfjs-logic.js hosted with ❤ by GitHub

Comments

Popular posts from this blog

JavaScript introduction to variables

Solutions to blocked URLs on Facebook

how to dump a postgresql database using from the terminal

How to set content disposition headers for express nodejs apps

How to get user's ip address in JavaScript