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


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

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

tf.where()函數用於根據指定條件返回第一張量或第二張量的元素。如果給定條件為真,則從第一個張量中選擇,否則從第二張量中選擇。

用法:

tf.where (condition, a, b)

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

  • condition:輸入條件必須具有布爾數據類型。
  • a:第一個輸入張量的尺寸與條件的大小相同。
  • b:第二個輸入張量的形狀與“a”兼容。它必須具有與“a”相同的數據類型。

返回值:它根據指定的條件返回元素的張量,是第一張量還是第二張量。



範例1:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Initializing a tensor of conditions
const cond = tf.tensor1d([true, false, true, false], 'bool');
  
// Initializing two tensors
const a = tf.tensor1d([-2 , 4, -6, 8]);
const b = tf.tensor1d([2, -4, 6, -8]);
  
// Calling the .where() function
a.where(cond, b).print();

輸出:

Tensor
   [-2, -4, -6, -8]

範例2:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Using a tensor of condition along with two tensors of 
// same datatype values as the parameters of the .where() function
tf.tensor1d([10, 20, 30, 40]).
where(tf.tensor1d([true, false, true, false], 'bool'), 
tf.tensor1d([100, 200, 300, 400])).print();

輸出:

Tensor
   [10, 200, 30, 400]

Referenec:https://js.tensorflow.org/api/1.0.0/#where

相關用法


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