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


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

Tensorflow.js是一個開放源代碼庫,由Google開發,用於在瀏覽器或節點環境中運行機器學習模型以及深度學習神經網絡。

.util.assert()函數用於斷言該函數中作為參數的表達式為true。如果不正確,則將引發錯誤以及該方法中所述的消息。

用法:

tf.util.assert(expr, msg)

參數:該函數接受以下兩個參數。

  • expr:這是要聲明的表達式,它是布爾類型的。
  • msg(()=>字符串):當表達式不為真且拋出錯誤時,此函數將返回所聲明的消息。在此,出於性能原因使用函數。

返回值:它返回void。



範例1:當陳述的表達式為真時。

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining a constant x
const y = 5;
  
// Calling util.assert() method and
// printing output
tf.util.assert(y === 5, (msg) => {});
  
console.log("Successfully Executed, No Error Occurred")
console.log("Condition True")

輸出:

Successfully Executed, No Error Occurred
Condition True

範例2:當聲明的表達式為false並引發錯誤時。

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining a constant x and
// all the parameters
const y = 3.6;
var exp = (y == 3.0)
var msg = 'value of y is not 3.6';
  
// Calling util.assert() method and
// printing output
var z = tf.util.assert(exp, msg);
console.log("true");

輸出:

throw new Error(typeof msg === 'string' ? msg:msg());
Error:value of y is not 3.6

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

相關用法


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