Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 1D tensor to regular javascript array?

How to convert 1D tensor to regular Javascript array in Tensorflow.js?

My 1D Tensor is like this:

Tensor [-0.0005436, -0.0021222, 0.0006213, 0.0014624, 0.0012601, 0.0007024, -0.0001113, -0.0011119, -0.0021328, -0.0031764]
like image 842
user1636258 Avatar asked Jun 18 '18 01:06

user1636258


People also ask

How do you convert a tensor to an array?

To convert back from tensor to numpy array you can simply run . eval() on the transformed tensor.

What is a tensor in TensorFlow JS?

The central unit of data in TensorFlow. js is the tf. Tensor : a set of values shaped into an array of one or more dimensions. tf. Tensor s are very similar to multidimensional arrays.

Which of the following will be used to convert NumPy array to TensorFlow tensor?

convert_to_tensor() method from the TensorFlow library is used to convert a NumPy array into a Tensor.


2 Answers

You can use .dataSync() to get the values of a tensor in a TypedArray and if you want a standard JS array you can use Array.from(), which creates arrays out of array-like objects.

const tensor = tf.tensor1d([1, 2, 3]);
const values = tensor.dataSync();
const arr = Array.from(values);
console.log(values);
console.log(arr);
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>

Keep in mind using .dataSync() blocks the UI thread until the values are ready, which can cause performance issues. If you want to load the values asynchronously you can use .data(), which returns a Promise resolving to the TypedArray.

like image 149
Sebastian Speitel Avatar answered Sep 26 '22 06:09

Sebastian Speitel


To convert tf.tensor to plain js array there are array() and arraySync() methods.

e.g. tf.tensor([1, 2, 5]).arraySync()

like image 24
Maksim Shamihulau Avatar answered Sep 26 '22 06:09

Maksim Shamihulau