输入输出张量如何用于 tensorflowjs 层 api

How does the input output tensors work for tensorflowjs layers api

我有 8 个输入和 1 个输出的分类问题。我创建了以下模型:

const hidden = tf.layers.dense({
  units: 8,
  inputShape: [58, 8, 8],
  activation: 'sigmoid'
});
const output = tf.layers.dense({
  units: 1,
  activation: 'softmax'
});

var model = tf.sequential({
  layers: [
  hidden,
  output
  ]
});

现在当我预测

const prediction = model.predict(inputTensor);
prediction.print();

我预计此预测有 1 个输出值,但我得到更多,这是如何工作的?

这些是形状

console.log(input.shape) // [1, 58, 8, 8]
console.log(prediction.shape) // [1, 58, 8, 1]

输出如下所示:

   [[[[0.8124214],
       [0.8544047],
       [0.6427221],
       [0.5753598],
       [0.5      ],
       [0.5      ],
       [0.5      ],
       [0.5      ]],

      [[0.7638108],
       [0.642349 ],
       [0.5315424],
       [0.6282103],
       [0.5      ],
       [0.5      ],
       [0.5      ],
       [0.5      ]],
      ... 58 of these

input.shape [1, 58, 8, 8],对应如下:

  • 1 是批量大小。 More 批量大小
  • 58,8,8是网络入口中指定的inputShape

同理output.shape [1, 58, 8, 8],对应如下:

  • 1 仍然是批量大小
  • 58, 8 匹配 inputShape 的内部尺寸
  • 1 是网络值的最后一个单位。

如果只需要单位值,即形状为 [1, 1] 的图层,可以使用 tf.layers.flatten().

删除内部维度

const model = tf.sequential();

model.add(tf.layers.dense({units: 4, inputShape: [58, 8, 8]}));
model.add(tf.layers.flatten())
model.add(tf.layers.dense({units: 1}));
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
model.fit(tf.randomNormal([1, 58, 8, 8]), tf.randomNormal([1, 1]))
model.predict(tf.randomNormal([1, 58, 8, 8])).print()

// Inspect the inferred shape of the model's output, which equals
// `[null, 1]`. The 1st dimension is the undetermined batch dimension; the
// 2nd is the output size of the model's last layer.
console.log(JSON.stringify(model.outputs[0].shape));
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.1.2/dist/tf.min.js"></script>