如何使用Tensorflow.JS实现softmax

问题描述 投票:1回答:1

使用Tensorflow.JS,我正在尝试使用softmax激活函数在最后一个密集层上运行机器学习模型。当我尝试运行它时,我收到:

检查目标时出错:预期densed_Dense2具有形状[,1],但得到形状为[3,2]的数组。

如果注释掉fit函数并运行它,我将得到一个1x2数组(这是预期的,因为我在最后一层有2个单元,而我只参加了一个测试。

此外,当我将y变量更改为该数组:[[1,2,3]]时,它会进行训练(但我不认为这是正确的,因为ys不是最后一层的正确形状(2 )。

为了填补我的知识空白,我们将不胜感激。

var tf = require('@tensorflow/tfjs');

let xs = tf.tensor([
  [1,2],
  [2,1],
  [0,0]
]);

let ys = tf.tensor([
  [1,2],
  [2,1],
  [1,1]
]);

async function createModel () {


  const model = tf.sequential();
  model.add(tf.layers.dense({inputShape: [2], units: 32, activation: "relu"}));
  model.add(tf.layers.dense({units: 2}));
  model.compile({loss: "sparseCategoricalCrossentropy",optimizer:"adam"});

  //await model.fit(xs, ys, {epochs:1000});

  model.predict(tf.tensor([[1,2]])).print();
}

createModel();
machine-learning deep-learning neural-network tensorflow.js softmax
1个回答
1
投票

这是最后一层的softmax激活:

  const model = tf.sequential();
  model.add(tf.layers.dense({inputShape: [2], units: 32, activation: "relu"}));
  model.add(tf.layers.dense({units: 2, activation:'softmax'}));
  model.compile({loss: "sparseCategoricalCrossentropy",optimizer:"adam"});

  model.predict(tf.tensor([[1,2]])).print();

对于错误:

检查目标时出错:预期densed_Dense2具有形状[,1],但得到形状为[3,2]的数组。

您可以考虑给出的答案here

您的错误与损失函数sparseCategoricalCrossentropy有关,该函数期望将标签标记为tensor1d。如果将此损失功能更改为categoricalCrossentropy,它将起作用。两种损失的作用相同,只是标签的编码方式不同。但是正如问题所在,标签既没有为categoricalCrossentropy也没有为sparseCategoricalCrossentropy编码。

  • 使用sparseCategoricalCrossentropy时,标签是一维张量,其中值是类别的索引
  • 使用categoricalCrossentropy时,标签是二维张量,也称为一热编码
© www.soinside.com 2019 - 2024. All rights reserved.