Open In App

Tensorflow.js tf.layers.flatten() Function

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.



Return Value: It returns the flattened layer.

Example 1:




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.




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


Article Tags :