Tensorflow.js tf.TensorBuffer 类 .toTensor() 方法
Tensorflow.js是谷歌开发的一个开源库,用于在浏览器或节点环境中运行机器学习模型和深度学习神经网络。
tf.TensorBuffer 类 .toTensor()函数用于从指定的缓冲区及其值创建不可变的张量对象。
句法:
toTensor ()
参数:此函数不接受任何参数。
返回值:返回创建的不可变张量对象。
示例 1:
Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
// Creating a buffer of 2*2 dimensions
const buffer = tf.buffer([2, 2]);
// Setting values at particular indices.
buffer.set(5, 0, 0);
buffer.set(10, 1, 0);
// Converting the above buffer back
// to a tensor value to print with
// the help of .toTensor() function
buffer.toTensor().print();
Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
// Creating a buffer of 3*3 dimensions
const buffer = tf.buffer([3, 3]);
// Setting values at particular indices.
buffer.set(5, 0, 0);
buffer.set(10, 0, 1);
buffer.set(15, 1, 0);
buffer.set(20, 1, 1);
buffer.set(25, 2, 0);
buffer.set(30, 2, 1);
buffer.set(35, 2, 2);
// Converting the above buffer back
// to a tensor value to print with
// the help of .toTensor() function
buffer.toTensor().print()
输出:
Tensor
[[5 , 0],
[10, 0]]
示例 2:
Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
// Creating a buffer of 3*3 dimensions
const buffer = tf.buffer([3, 3]);
// Setting values at particular indices.
buffer.set(5, 0, 0);
buffer.set(10, 0, 1);
buffer.set(15, 1, 0);
buffer.set(20, 1, 1);
buffer.set(25, 2, 0);
buffer.set(30, 2, 1);
buffer.set(35, 2, 2);
// Converting the above buffer back
// to a tensor value to print with
// the help of .toTensor() function
buffer.toTensor().print()
输出:
Tensor
[[5 , 10, 0 ],
[15, 20, 0 ],
[25, 30, 35]]
参考: https://js.tensorflow.org/api/latest/#tf.TensorBuffer.toTensor