Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Tensorflow.js tf.LayersModel class .fitDataset() Method

  • Last Updated : 18 Aug, 2021

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.LayersModel class .fitDataset() method is used to trains the layer model by using a dataset object.

Syntax:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

LayerModel.fitDataset(dataset, args);

Parameters: This method accepts the following parameters:

  • dataset: It is an input value in the form of the dataset by which we train our layer model.
  • args: It Is an object that contains the following values:
    • batchesPerEpoch: It is the number of batches in every epoch. It depends on the size of the batch as batch size increases its size decreases.
    • epochs: It is the total number of iteration in the training dataset during the training model. It should be an integer value.
    • initialEpoch: It is used to define the epoch’s value at which to start training.
    • validationData: It is used to give an estimate of the final model when selecting between final models.
    • verbose: It help in showing the progress for each epoch. If the value is 0 – It means no printed message during fit() call. If the value is 1 – It means in Node.js, it prints the progress bar. In the browser, it shows no action. Value 1 is the default value . 2 – Value 2 is not implemented yet.
    • classWeight: It is used for weighting the loss function. It can be useful to tell the model to pay more attention to samples from an under-represented class.
    • callbacks: It defines a list of callbacks to be called during training. Variable can have one or more of these callbacks onTrainBegin( ), onTrainEnd( ), onEpochBegin( ), onEpochEnd( ), onBatchBegin( ), onBatchEnd( ), onYield( ).
    • validationBatchSize: It is the number that defines the size of the batch. It is used to validate the batch size. It means that we can’t put all datasets at once that exceeding this value. its defaults value is 32.
    • validationBatches: It is used to validate the batches of samples. It is used to draw validation data for validation purposes at every end of an epoch.
    • yieldEvery: It defines the configuration of the frequency of yielding the main thread to other tasks. It can be auto, It means the yielding happens at a certain frame rate. batch, If the value is this, It yields every batch. epoch, If the value is this, It yields every epoch. any number, If the value is any number, it yields every number milliseconds. never, If the value is this, it never yields.

Returns: Promise< History >



 

Example 1: In this example, we will train our layer model with CSV dataset.

Javascript




import * as tf from "@tensorflow/tfjs"
  
// Path for the CSV file 
const gfg_CsvFile =
  
async function run() {
  
    // Creating model
    const gfg_LayerModel = tf.sequential();
  
    // Adding layer to model
    const config = { units: 1, inputShape: [12] }
    const gfg_layer = tf.layers.dense(config);
    gfg_LayerModel.add(gfg_layer);
  
    // Compiling the model
    const opt = tf.train.sgd(0.00000001)
    gfg_LayerModel.compile({ optimizer: opt, 
            loss: 'meanSquaredError' });
  
    // Here we want to predict column tax
    const config2 = { columnConfigs: {
             rad: { isLabel: true } } };
  
    const csvDataset = tf.data.csv(gfg_CsvFile, config2);
  
    // Creating dataset for training
    const flattenedDataset =
        csvDataset.map(({ xs, ys }) => {
            return { xs: Object.values(xs), 
                    ys: Object.values(ys) };
        }).batch(6);
  
    // Training the model
    const Tm = await gfg_LayerModel.fitDataset(
            flattenedDataset, { epochs: 10 });
  
    for (let i = 0; i < 6; i++) {
        console.log(Tm.history.loss[i])
    }
}
run();

Output:

41480.109375
28887.93359375
20162.228515625
14115.478515625
9924.9404296875
7020.56005859375

Example 2: In this example, we will train our layer model with a dataset of the array.

Javascript




import * as tf from "@tensorflow/tfjs"
  
async function run() {
  
    // Creating Layer model
    const gfg_LayerModel = tf.sequential();
  
    // Adding layer to model
    const config = { units: 4, inputShape: [4] }
    const gfg_layer = tf.layers.dense(config);
    gfg_LayerModel.add(gfg_layer);
  
    // Compiling the model
    const config2 = { optimizer: 'sgd', loss: 'meanSquaredError' }
    gfg_LayerModel.compile(config2);
  
    // Creating Datasets for training
    const array1 = [
        [1, 2, 3, 4],
        [1, 4, 6, 8],
        [1, 3, 4, 7],
        [3, 4, 7, 8]
    ];
    const array2 = [1, 1, 1, 1];
    const arrData1 = tf.data.array(array1);
    const arrData2 = tf.data.array(array2);
  
    const config3 = { xs: arrData1, ys: arrData2 }
    const arrayDataset = tf.data.zip(config3)
    const ArrayDataset = arrayDataset.batch(4);
  
    // Training the model
    const Tm = await gfg_LayerModel.fitDataset(
            ArrayDataset, { epochs: 4 });
  
    // Printing the loss after training
    console.log("Loss After Training Layer Model"
        + Tm.history.loss[0]);
}
run();

Output:

Loss After Training Layer Model 4.386415958404541

Reference: https://js.tensorflow.org/api/latest/#tf.LayersModel.fitDataset




My Personal Notes arrow_drop_up
Recommended Articles
Page :