Tensorflow.js tf.LayersModel Class
Last Updated :
12 Dec, 2022
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. Tensorflow. js tf.LayerModel class is used to training, interface and evaluation of model. It have many method for training, evaluation, prediction and saving.
Syntax:
tf.LayerModel.method(args);
Parameters:
- args: Different method except different parameters.
Returns: Different methods returned different values tf.tensor object, etc.
Below we will see the implementation of methods of tf.LayerModel class.
Example 1: In this example, will see trainOnBatch() method which is used to apply optimizer update on a single batch of data. It takes two tensor first as input value tensor and second as target tensor. It returns a promise of number.
JavaScript
import * as tf from "@tensorflow/tfjs"
async function run() {
// Training Model
const gfg = tf.sequential();
// Adding layer to model
const layer = tf.layers.dense({units:3,
inputShape : [5]});
gfg.add(layer);
// Compiling our model
const config = {optimizer:'sgd',
loss:'meanSquaredError'};
gfg.compile(config);
// Test tensor and target tensor
const layerOne = tf.ones([3,5]);
const layerTwo = tf.ones([3,3]);
// Apply trainOnBatch to out test data
const result =
await gfg.trainOnBatch(layerOne, layerTwo);
// Printing out result
console.log(result);
}
// Function call
await run();
Output:
3.683875560760498
Example 2: In this example, we will see getLayer() method which is used to fetch layers with the help of its name of the index. It takes the name of the layer of the index of the layer as parameter. It returns tf.layers.Layer.
JavaScript
import * as tf from "@tensorflow/tfjs"
// Defining model
const gfg_Model = tf.sequential();
// Adding layers
const config = {units: 4, inputShape: [1] };
const layer = tf.layers.dense( config);;
gfg_Model.add( layer);
const config2 = {units: 2, inputShape: [3] , activation: 'sigmoid'};
const layer2 = tf.layers.dense( config2 );;
gfg_Model.add(layer2);
// Calling getLayer() method
const layer_1 = gfg_Model.getLayer('denselayer', 1);
// Printing layer config
console.log(layer_1.getConfig());
Output:
{
"units": 2,
"activation": "sigmoid",
"useBias": true,
"kernelInitializer": {
"className": "VarianceScaling",
"config": {
"scale": 1,
"mode": "fanAvg",
"distribution": "normal",
"seed": null
}
},
"biasInitializer": {
"className": "Zeros",
"config": {}
},
"kernelRegularizer": null,
"biasRegularizer": null,
"activityRegularizer": null,
"kernelConstraint": null,
"biasConstraint": null,
"name": "dense_Dense53",
"trainable": true,
"batchInputShape": [
null,
3
],
"dtype": "float32"
}
Reference: https://js.tensorflow.org/api/latest/#class:LayersModel