我正在学习tensorflow.js Udemy课程,并且老师在张量对象上使用了函数get
,并传入行和列索引以返回该位置的值。我无法在文档中找到此方法,并且在nodejs内也无法使用,函数get()似乎不存在。
这是他的代码,他正在自定义控制台https://stephengrider.github.io/JSPlaygrounds/
的浏览器中运行 const data = tf.tensor([
[10, 20, 30],
[40, 50, 60]
]);
data.get(1, 2); // returns 60 in video, in browser
这是我的代码,这是我使其正常工作的唯一方法,但看起来却很丑陋:
const tf = require('@tensorflow/tfjs-node');
(async () => {
const data = tf.tensor([
[10, 20, 30],
[40, 50, 60]
]);
let lastIndex = (await data.data())[5];
console.log(lastIndex) // returns 60
})();
必须有一种更好的方法来访问特定索引处的值。 data()
方法仅从张量返回所有值的数组,而我无法找到一种通过行,列语法访问值的方法。
答案 0 :(得分:1)
get
自 v0.15.0 起已弃用,并已从 v1.0.0 中删除。因此,检索特定索引处的值的唯一方法是使用
tf.slice
,它将返回特定索引或
如果您想将值作为JavaScript号码检索,则可以使用其中一个
tf.data
和值或
tf.array
和坐标
使用tf.buffer
(async () => {
const data = tf.tensor([
[10, 20, 30],
[40, 50, 60]
]);
console.time()
let lastIndex = (await data.data())[5];
console.log(lastIndex) // returns 60
console.timeEnd()
// using slice
console.time()
data.slice([1, 2], [1, 1]).print()
console.timeEnd()
//using array and the coordinates
console.time()
const value = (await data.array())[1][2]
console.log(value)
console.timeEnd()
// using buffer
console.time()
const buffer = await data.buffer()
const value2 = buffer.get(1, 2)
console.log(value2)
console.timeEnd()
})();
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script>
</head>
<body>
</body>
</html>