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


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

Tensorflow.js是Google開發的開源庫,用於在瀏覽器或節點環境中運行機器學習模型和深度學習神經網絡。它還可以幫助開發人員使用JavaScript語言開發ML模型,並可以直接在瀏覽器或Node.js中使用ML。

tf.pad() 函數用於使用給定值和填充填充 tf.Tensor。

用法:

tf.pad(tensor, paddings, constantValue)

參數:此函數接受以下三個參數:

  • tensor:它是一個要填充的張量。
  • paddings:它是一個長度為 R 的數組,給定張量的秩,其中每個元素的長度為 2 個整數 ([pad_Before, pad_After]),指定應沿張量的每個維度給出多少填充。
  • constantValue:它是要使用的填充值。默認值為 0。

返回值:它返回tf.Tensor對象。



範例1:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Intializing 3d tensor and then using 
// .pad() function to print the result
tf.tensor3d([1, 2, 3, 4], [2, 2, 1])
  .pad([[0, 0], [1, 1], [2, 2]])
      .print();

輸出:

Tensor
    [[[0, 0, 0, 0, 0],
      [0, 0, 1, 0, 0],
      [0, 0, 2, 0, 0],
      [0, 0, 0, 0, 0]],

     [[0, 0, 0, 0, 0],
      [0, 0, 3, 0, 0],
      [0, 0, 4, 0, 0],
      [0, 0, 0, 0, 0]]]

範例2:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Intializing 2d tensor
let geek1 = tf.tensor2d([[1, 2], [3, 4]]);
  
// Using .pad() function.
let geek2 = geek1.pad([[0, 1], [2, 1]]);
  
// Printing the result.
geek2.print();

輸出:

Tensor
    [[0, 0, 1, 2, 0],
     [0, 0, 3, 4, 0],
     [0, 0, 0, 0, 0]]

參考:https://js.tensorflow.org/api/3.6.0/#pad

相關用法


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