如何将一维张量转换为常规 javascript 数组?
How to convert 1D tensor to regular javascript array?
如何将一维张量转换为 Tensorflow.js 中的常规 Javascript 数组?
我的一维张量是这样的:
Tensor [-0.0005436, -0.0021222, 0.0006213, 0.0014624, 0.0012601, 0.0007024, -0.0001113, -0.0011119, -0.0021328, -0.0031764]
您可以使用 .dataSync()
to get the values of a tensor in a TypedArray and if you want a standard JS array you can use Array.from()
,它从类似数组的对象中创建数组。
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/tfjs@0.14.1/dist/tf.min.js"></script>
请记住,使用 .dataSync()
会阻塞 UI 线程,直到值准备就绪,这可能会导致性能问题。如果您想异步加载值,您可以使用 .data()
, which returns a Promise 解析为 TypedArray。
要将 tf.tensor
转换为纯 js 数组,有 array()
和 arraySync()
方法。
例如tf.tensor([1, 2, 5]).arraySync()
如何将一维张量转换为 Tensorflow.js 中的常规 Javascript 数组?
我的一维张量是这样的:
Tensor [-0.0005436, -0.0021222, 0.0006213, 0.0014624, 0.0012601, 0.0007024, -0.0001113, -0.0011119, -0.0021328, -0.0031764]
您可以使用 .dataSync()
to get the values of a tensor in a TypedArray and if you want a standard JS array you can use Array.from()
,它从类似数组的对象中创建数组。
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/tfjs@0.14.1/dist/tf.min.js"></script>
请记住,使用 .dataSync()
会阻塞 UI 线程,直到值准备就绪,这可能会导致性能问题。如果您想异步加载值,您可以使用 .data()
, which returns a Promise 解析为 TypedArray。
要将 tf.tensor
转换为纯 js 数组,有 array()
和 arraySync()
方法。
例如tf.tensor([1, 2, 5]).arraySync()