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]
To convert back from tensor to numpy array you can simply run . eval() on the transformed tensor.
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.
convert_to_tensor() method from the TensorFlow library is used to convert a NumPy array into a Tensor.
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.
To convert tf.tensor
to plain js array there are array()
and arraySync()
methods.
e.g. tf.tensor([1, 2, 5]).arraySync()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With