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


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

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

Tensorflow.js tf.registerOp() 函數用於在 TensorFlow 中為圖模型執行器注冊 Ops(操作)。使用此函數,用戶不僅可以在 Tensorflow 中創建自定義 Ops,還可以覆蓋現有 Ops

用法:

tf.registerOp (name, opFunc)

Parameters: 以下是上述函數接受的參數,如下所示:

  • name: 這是字符串類型參數。該參數代表 Tensorflow Op 名稱。
  • opFunc: 這是對象類型參數。該參數接受 op 函數。在執行期間必須使用當前圖節點(包含 attr 和輸入)調用該函數,並且必須返回張量或張量列表。

返回值:它返回無效。

筆記:

  • 節點對象的輸入和屬性基於 TensorFlow op 注冊表。
  • 要檢查 NewOp Op 是否已注冊,請使用 Tensorflow.js tf.getRegisteredOp() 函數。

示例 1:使用校驗碼注冊新 Op NewOp 以及新 Op 函數的示例。

Javascript


// Importing the tensorflow.js library  
const tf = require("@tensorflow/tfjs");  
    
// Try to create a new Op 
const customOp = (node) => 
    tf.add( 
        node.inputs[0], node.inputs[1] 
    ); 
  
// Try to register a new Op NewOp 
const x = tf.registerOp('NewOp', customOp); 
  
// Check code and new op functioning 
const a = tf.scalar(1); 
const b = tf.tensor1d([1, 2, 3, 4]); 
const name = tf.getRegisteredOp('NewOp'); 
const ans = name.customExecutor({"inputs":[a,b]}); 
console.log(ans.print())

輸出:

Tensor
    [2, 3, 4, 5]
undefined

示例 2:使用檢查代碼覆蓋現有 Op 的示例以及覆蓋 Op 的函數。

Javascript


// Importing the tensorflow.js library  
const tf = require("@tensorflow/tfjs");  
  
// Try to override add Op with sub op 
const x = tf.registerOp(tf.add, tf.sub); 
  
// Check code and override op functioning 
const a = tf.tensor1d([10, 20, 30, 40]); 
const b = tf.scalar(5); 
const ans = tf.add(a,b); 
console.log(ans.print())

輸出:

Tensor
    [15, 25, 35, 45]
undefined

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



相關用法


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