Tensorflow.js tf.scalar() Function
Last Updated :
27 Apr, 2023
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 .scalar() function is used to create a scalar type of tensor means. A scalar is a zero-dimension array and is also called a rank-0 Tensor. A scalar is created using .scalar() function.
Syntax:
t.scalar( value, dataType )
Parameters:
- value: The value of the scalar. The value can be a number, string, Uint8Array[ ], or boolean.
- dataType [Optional]: The data type of the value. It can be an int32, float32, bool, complex64, or string.
Return Value: It returns the Tensor Object.
Creating a Scalar: In this example, we are creating a new scalar, which means a tensor of only one value.
Example 1:
Javascript
import * as tf from "@tensorflow/tfjs"
var value = 12
var tens = tf.scalar(value)
tens.print();
|
Output:
Tensor
12
Creating a scalar of a specific data type: In this example, we are creating a scalar of a specific data type. Note that the data type should only int32, float32, bool, complex64, or string.
Example 2:
Javascript
import * as tf from "@tensorflow/tfjs"
var int_tensor = tf.scalar(12, 'int32' )
int_tensor.print()
var str_tensor = tf.scalar( "GFG" , "string" )
str_tensor.print()
var float_tensor = tf.scalar(12.6, "float32" )
float_tensor.print();
var bool_tensor1 = tf.scalar( true , "bool" )
bool_tensor1.print()
var bool_tensor2 = tf.scalar(0, "bool" )
bool_tensor2.print()
|
Output:
Tensor
12
Tensor
GFG
Tensor
12.600000381469727
Tensor
true
Tensor
false
Note: You can also create a scalar using tf.tensor() function. Let’s see the example
Creating a Scalar using tf.tensor() Function:
Example 3:
Javascript
import * as tf from "@tensorflow/tfjs"
var tens = tf.tensor(12, [], "int32" )
tens.print()
|
Here we are providing the second parameter of the function an empty array because we are creating a scalar and a scalar is a rank-0 tensor.
Output:
Tensor
12
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...