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


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

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

.addLoss() 函數用於將損失附加到所述層。此外,損失可能取決於幾個輸入張量,例如操作損失取決於所述層的輸入。

用法:

addLoss(losses)

參數:

  • losses:它是聲明的損失。它可以是RegularizerFn 或RegularizerFn[] 類型。

返回值:它返回void。



範例1:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating a model
const model = tf.sequential();
  
// Adding a layer
model.add(tf.layers.dense({units:1, inputShape:[3]}));
  
// Defining input
const input = tf.tensor1d([1, 2, 3, 4]);
  
// Calling addLoss() method with its 
// parameter
const res = model.layers[0].addLoss([tf.abs(input)]);
  
// Printing output
console.log(JSON.stringify(input));
model.layers[0].getWeights()[0].print();

輸出:

{"kept":false,"isDisposedInternal":false,"shape":[4],"dtype":"float32",
"size":4,"strides":[],"dataId":{"id":82},"id":124,"rankType":"1","scopeId":61}
Tensor
    [[0.143441  ],
     [-0.58002  ],
     [-0.5836995]]

範例2:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating a model
const model = tf.sequential();
  
// Adding layers
model.add(tf.layers.dense({units:1, inputShape:[3]}));
model.add(tf.layers.dense({units:4}));
model.add(tf.layers.dense({units:9, inputShape:[11]}));
  
// Defining inputs
const input1 = tf.tensor1d([0.5, 0.2, -33, null]);
const input2 = tf.tensor1d([0.33, 0.5, -1]);
const input3 = tf.tensor1d([1, 0.44]);
  
// Calling addLoss() method with its 
// parameter
const res1 = model.layers[0].addLoss([tf.cos(input1)]);
const res2 = model.layers[0].addLoss([tf.sin(input2)]);
const res3 = model.layers[0].addLoss([tf.tan(input3)]);
  
// Printing outputs
console.log(JSON.stringify(input1));
console.log(JSON.stringify(input2));
console.log(JSON.stringify(input3));
model.layers[0].getWeights()[0].print();

輸出:

 {"kept":false,"isDisposedInternal":false,"shape":[4],"dtype":"float32",
 "size":4,"strides":[],"dataId":{"id":169},"id":261,"rankType":"1","scopeId":112}
{"kept":false,"isDisposedInternal":false,"shape":[3],"dtype":"float32",
"size":3,"strides":[],"dataId":{"id":170},"id":262,"rankType":"1","scopeId":112}
{"kept":false,"isDisposedInternal":false,"shape":[2],"dtype":"float32",
"size":2,"strides":[],"dataId":{"id":171},"id":263,"rankType":"1","scopeId":112}
Tensor
    [[-0.0062826],
     [0.0883235 ],
     [-1.0633234]]

參考:https://js.tensorflow.org/api/latest/#tf.layers.Layer.addLoss




相關用法


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