Open In App

Tensorflow.js tf.layers.flatten() Function

Last Updated : 25 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.

The tf.layers.flatten() function is used to flatten the input, without affecting the batch size. A Flatten layer flattens each batch in the inputs to 1-dimension.

Syntax:

tf.layers.flatten( args? )

Parameters: It takes as input an object: args (Object). It is optional to provide args object as input. Following are the fields you can provide in the args object.

  • dataFormat (‘channelsFirst’ or ‘channelsLast’): It is the image data format.
  • inputShape ((null | number)[]): It is used to create an input layer to insert before this layer.
  • batchInputShape ((null | number)[]): It is used to create an input layer to insert before this layer. If both inputShape and batchInputShape are defined, batchInputShape will be used.
  • batchSize (number): If inputShape is specified and batchInputShape is not specified, batchSize is used to construct the batchInputShape.
  • dtype (‘float32’|’int32’|’bool’|’complex64’|’string’): Used to define the data type for this layer.
  • name (string): Used to provide a name to the layer.
  • trainable (boolean): Used to specify whether the weights of this layer are updatable by fit. Defaults value os true.
  • weights (tf.Tensor[]): Used to provide initial weight values of the layer.

Return Value: It returns the flattened layer.

Example 1:

Javascript




const tf = require("@tensorflow/tfjs")
  
const input = tf.input({shape: [5, 4]});
  
// Creating flattened layer
const flattenLayer = tf.layers.flatten();
  
// Printing the shape
console.log(JSON.stringify(flattenLayer.apply(input).shape));


Output: In output, we can see the shape of the flatten layer equals `[null, 12]` as 2nd dimension is 4 * 3, i.e. the result of the flattening.

[null, 20]

Example 2: In this example, we will provide the name field in the args object as input.

Javascript




const tf = require("@tensorflow/tfjs")
  
const input = tf.input({shape: [4, 3]});
  
// Creating flattened layer
const flattenLayer = tf.layers.flatten({name:'NewLayer1'});
  
// Printing the name and shape
console.log("Name of the layer: " 
    + flattenLayer.apply(input).name)
  
console.log(JSON.stringify(
    flattenLayer.apply(input).shape));


Output:

Name of the layer: NewLayer1/NewLayer1
[null, 12]

Reference: https://js.tensorflow.org/api/latest/#layers.flatten



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads