📜  Tensorflow.js tf.TensorBuffer 类

📅  最后修改于: 2022-05-13 01:56:28.158000             🧑  作者: Mango

Tensorflow.js tf.TensorBuffer 类

Tensorflow.js是谷歌开发的一个开源库,用于在浏览器或节点环境中运行机器学习模型和深度学习神经网络。

这个 TensorBuffer 类可变对象类似于tf.Tensor ,它允许用户在转换为不可变 tf.Tensor 之前在指定位置设置值。为了创建张量缓冲区,使用 tf.buffer()。

这个TensorBuffer 类具有三个内置函数,如下所示:

  • tf.TensorBuffer 类 .set()函数
  • tf.TensorBuffer 类 .get()函数
  • tf.TensorBuffer 类 .toTensor()函数

tf.TensorBuffer 类 .set()函数用于在指定位置的缓冲区中设置给定值。

示例 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
buffer.toTensor().print();


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); 
  
// Getting the values for the
// specified indices with the
// help of .get() function
console.log(buffer.get(0, 0));
console.log(buffer.get(1, 0));


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();


输出:

Tensor
  [[5 , 0],
   [10, 0]]

tf.TensorBuffer 类 .get()函数用于返回给定位置的指定缓冲区中的值。

示例 2:

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); 
  
// Getting the values for the
// specified indices with the
// help of .get() function
console.log(buffer.get(0, 0));
console.log(buffer.get(1, 0));

输出: tf.TensorBuffer 类 .toTensor()函数用于从指定的缓冲区及其值创建不可变的张量对象。

5
10 

示例 3:

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();

输出:

Tensor
 [[5 , 0],

参考: https://js.tensorflow.org/api/latest/#class:TensorBuffer