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.registerOp() function is used to register an Ops(operations) for graph model executor in TensorFlow. Using this function users can not only create custom Ops in Tensorflow but also able to override the existing ones
Syntax:
tf.registerOp (name, opFunc)
Parameters: Following are the parameters accepted by the above function and the same are illustrated below:
- name: This is the string type parameter. This parameter represents the Tensorflow Op name.
- opFunc: This is the Object type parameter. This parameter accepts an op function. The function must be called with the current graph node (contains attr and inputs) during execution and has to return either tensor or a list of tensors.
Return Value: It returns void.
Note:
- The node object’s inputs and attrs are based on the TensorFlow op registry.
- To check if NewOp Op is registered or not, use Tensorflow.js tf.getRegisteredOp() function.
Example 1: Example of registering a new Op NewOp with check code and functioning of new Op.
// Importing the tensorflow.js library const tf = require( "@tensorflow/tfjs" );
// Try to create a new Op const customOp = (node) => tf.add(
node.inputs[0], node.inputs[1]
);
// Try to register a new Op NewOp const x = tf.registerOp( 'NewOp' , customOp);
// Check code and new op functioning const a = tf.scalar(1); const b = tf.tensor1d([1, 2, 3, 4]); const name = tf.getRegisteredOp( 'NewOp' );
const ans = name.customExecutor({ "inputs" :[a,b]});
console.log(ans.print()) |
Output:
Tensor [2, 3, 4, 5] undefined
Example 2: Example of overriding an existing Op with check code and functioning of override Op.
// Importing the tensorflow.js library const tf = require( "@tensorflow/tfjs" );
// Try to override add Op with sub op const x = tf.registerOp(tf.add, tf.sub); // Check code and override op functioning const a = tf.tensor1d([10, 20, 30, 40]); const b = tf.scalar(5); const ans = tf.add(a,b); console.log(ans.print()) |
Output:
Tensor [15, 25, 35, 45] undefined
Reference: https://js.tensorflow.org/api/latest/#registerOp