javascript - 将 TensorFlow 中的张量值转换为常规 Javascript 数组
问题描述
我在两个一维数组(a,b)上使用了 TensorFlow.js 框架中的 outerProduct 函数,但我发现很难以常规 javascript 格式获取结果张量的值。
即使在使用 .dataSync 和 Array.from() 之后,我仍然无法获得预期的输出格式。两个一维数组之间的结果外积应该给出一个二维数组,但我得到的是一维数组。
const a = tf.tensor1d([1, 2]);
const b = tf.tensor1d([3, 4]);
const tensor = tf.outerProduct(b, a);
const values = tensor.dataSync();
const array1 = Array.from(values);
控制台.log(array1);
预期的结果是 array1 = [ [ 3, 6 ] , [ 4, 8 ] ],但我得到 array1 = [ 3, 6, 4, 8 ]
解决方案
版本 < 15
tf.data
or的结果tf.dataSync
始终是一个展平数组。但是可以使用张量的形状来使用map和reduce获得一个多维数组。
const x = tf.tensor3d([1, 2 , 3, 4 , 5, 6, 7, 8], [2, 4, 1]);
x.print()
// flatten array
let arr = x.dataSync()
//convert to multiple dimensional array
shape = x.shape
shape.reverse().map(a => {
arr = arr.reduce((b, c) => {
latest = b[b.length - 1]
latest.length < a ? latest.push(c) : b.push([c])
return b
}, [[]])
console.log(arr)
})
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.14.1"> </script>
</head>
<body>
</body>
</html>
从版本 0.15
推荐阅读
- schemacrawler - 有没有办法在 schemacrawler 图表上显示鱼尾纹?
- c# - C# - IoC - WebAPI 2 上的 Autofac 依赖注入
- bash - 在构建 bash 提示时终止后台进程
- amazon-web-services - 如何从 SQS 队列中获取所有消息直到队列为空?
- linux - Linux上如何同步多个独立应用的文件I/O?
- javascript - 在服务器上创建和测试 Javascript 动态表单?
- python - 遍历多个字符串列表以找到一个公共值
- python - 如何在 matplot/python 中绘制这样的图表?
- javascript - AJAX 只显示/隐藏开始/停止一次?
- php - 角保存下载文件