當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Tensorflow.js tf.buffer()用法及代碼示例

Tensorflow.js是Google開發的開源庫,用於在瀏覽器或節點環境中運行機器學習模型和深度學習神經網絡。

tf.buffer()函數用於為指定的數據類型和形狀創建一個空的Tensor緩衝區。使用buffer.set()函數在創建的緩衝區中設置值。

用法:

tf.buffer (shape, dtype, values)

參數:此函數接受三個參數,如下所示:

  • shape:整數數組,定義輸出張量的形狀。
  • dtype:創建的緩衝區的數據類型。默認值為‘float32’。此參數是可選的。
  • values:創建的緩衝區的值。默認值為零。此參數是可選的。

返回值:此函數僅創建緩衝區,因此不返回任何值。



範例1:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating a buffer of [2, 2] shape
const buffer = tf.buffer([2, 2]);
  
// Getting the created buffer in the
// form of Tensor of zeros values 
// as no values are set in the buffer
buffer.toTensor().print();

輸出:

Tensor
   [[0, 0],
    [0, 0]]

範例2:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating a buffer of [3, 3] shape 
const buffer = tf.buffer([3, 3]);
  
// Setting values in the created buffer
// at particular indices
buffer.set(10, 2, 0);
buffer.set(15, 0, 1);
buffer.set(20, 1, 2);
  
// Getting the buffer in the form of Tensor
// along with the set values
buffer.toTensor().print();

輸出:

Tensor
   [[0 , 15, 0 ],
    [0 , 0 , 20],
    [10, 0 , 0 ]]

參考:https://js.tensorflow.org/api/latest/#buffer

相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 Tensorflow.js tf.buffer() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。