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]]]
]
];
// 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) |
Comments
Post a Comment