📜  Tensorflow.js tf.losses.softmaxCrossEntropy()函数

📅  最后修改于: 2022-05-13 01:56:53.044000             🧑  作者: Mango

Tensorflow.js tf.losses.softmaxCrossEntropy()函数

Tensorflow.js是谷歌开发的一个开源库,用于在浏览器或节点环境中运行机器学习模型和深度学习神经网络。

Tensorflow.js tf.losses.softmaxrossEntropy()函数计算两个张量之间的 softmax 交叉熵损失并返回一个新张量。

句法:

tf.losses.softmaxCrossEntropy(onehotLabels, 
    logits, weights, labelSmoothing, reduction)

参数:该函数接受五个参数(其中最后三个是可选的),如下图所示:

  • onehot 标签: 是与预测具有相同维度的热编码标签。
  • logits:它是预测的输出。
  • 权重:这些是那些秩为 0 或 1 的张量,它们必须是可广泛铸造的以变形。
  • labelSmoothing:如果此参数的值大于 0,则对标签进行平滑处理。
  • 减少:这是适用于损失的减少类型。它必须是缩减类型。

注意:参数如 weights、labelSmoothingreduction是可选的。

返回值:它返回一个在两个张量之间具有 softmax 交叉熵损失的张量。

Javascript
// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
 
// Creating onehotLabels tensor
const a  = tf.tensor2d([[1, 4, 5], [5, 5, 7]]);
 
// Creating logits tensor
const b    = tf.tensor2d([[3, 2, 5], [3, 2, 7]])
 
// Computing soft max cross entropy distance
softmax_cross_entropy = tf.losses.softmaxCrossEntropy(a, b)
softmax_cross_entropy.print();


Javascript
// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
 
// const tf = require("@tensorflow/tfjs")
 
// Creating labels tensor
const a = tf.tensor2d([[1,2,3,4,5], [7,8,9,10,11]])
 
// Creating predictions tensor
const b = tf.tensor2d([[6,735,8,59,10], [45,34,322,2,3]])
 
const c = tf.tensor2d([[4,34,34,2,4],[65,34,3,2,3]])
 
// Computing cross entropy  with an option parameter number
softmax_cross_entropy = tf.losses.softmaxCrossEntropy(a, b, 5)
softmax_cross_entropy.print();


输出:

Tensor
   30.55956268310547

示例 2:在此示例中,我们传递了一个可选参数,即标签平滑。如果大于 0,则平滑标签。

Javascript

// Importing the tensorflow.Js library
import * as tf from "@tensorflow/tfjs"
 
// const tf = require("@tensorflow/tfjs")
 
// Creating labels tensor
const a = tf.tensor2d([[1,2,3,4,5], [7,8,9,10,11]])
 
// Creating predictions tensor
const b = tf.tensor2d([[6,735,8,59,10], [45,34,322,2,3]])
 
const c = tf.tensor2d([[4,34,34,2,4],[65,34,3,2,3]])
 
// Computing cross entropy  with an option parameter number
softmax_cross_entropy = tf.losses.softmaxCrossEntropy(a, b, 5)
softmax_cross_entropy.print();


输出:

Tensor
    50477.5

参考: https://js.tensorflow.org/api/latest/#losses.softmaxCrossEntropy