hamsterman
hamsterman

Reputation: 91

Tensorflow.js tf.Tensor to JS number

I am working a bit with Tensorflow.js and I want to plot some data that are stored as tf.Tensors. I cannot find a method that converts them to ordinary JS numbers.

const a = tf.Scalar(1)
const b = tf.Scalar(2)
var array = []
// Now o want to push the numbers 1 and 2 to mye array
array.push(a)
array.push(b)

This code gives my an array of tensor objects. I want an array of numbers. Any idea of how to proceed? Thank you.

Upvotes: 2

Views: 2611

Answers (3)

Yas
Yas

Reputation: 5481

scalar.get()

const a = tf.scalar(1)
const b = tf.scalar(2)
const array = [a, b].map(s => s.get()); // array [1, 2]

Upvotes: 0

Sebastian Speitel
Sebastian Speitel

Reputation: 7346

.dataSync() downloads the value of the GPU and returns a Float32Array of the values contained in the Tensor. So if you want to store the values as Tensors in the array and want to get an array of Numbers out of it you could map it using map() to create an array of the downloaded values and because you are using scalars in the example you can directly map to the first element in the Float32Array to get its value:

let values = array.map(t => t.dataSync()[0])

Example:

const a = tf.scalar(1)
const b = tf.scalar(2)
var array = []
array.push(a)
array.push(b)

let values = array.map(t => t.dataSync()[0])
console.log(values);
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]">
</script>

Upvotes: 2

Md Johirul Islam
Md Johirul Islam

Reputation: 5162

You can use a.get() and b.get() to get their values. The working code is:

const a = tf.scalar(1)
const b = tf.scalar(2)
var array = []
// Now o want to push the numbers 1 and 2 to mye array
array.push(a.get())
array.push(b.get())
console.log(array) // Outputs [1,2]

You can try the working code in Codepen

Upvotes: 2

Related Questions