GeeksforGeeks App
Open App
Browser
Continue

# Tensorflow.js tf.scalar() 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 .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

 `// Importing the tensorflow.js library``import * as tf from ``"@tensorflow/tfjs"` `// Value of a scalar``var` `value = 12` `// Creating the value of a scalar``var` `tens = tf.scalar(value)` `// Printing the scalar``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

 `// Importing the tensorflow.js library``import * as tf from ``"@tensorflow/tfjs"` `// Creating a scalar using int value``var` `int_tensor = tf.scalar(12, ``'int32'``)` `int_tensor.print()` `// Creating a scalar using string value``var` `str_tensor = tf.scalar(``"GFG"``, ``"string"``)` `str_tensor.print()` `// Creating a scalar using float value``var` `float_tensor = tf.scalar(12.6, ``"float32"``)` `float_tensor.print();` `// Creating a scalar using bool value``var` `bool_tensor1 = tf.scalar(``true``, ``"bool"``)` `bool_tensor1.print()` `// Creating a scalar using bool(0 and 1) type``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

 `// Importing the tensorflow.js library``import * as tf from ``"@tensorflow/tfjs"` `// Creating a scalar using int tf.tensor()``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```

My Personal Notes arrow_drop_up
Related Tutorials