tensorflow.js层API的输入输出张量如何工作

时间:2019-06-23 19:37:17

标签: javascript tensorflow machine-learning tensorflow.js

我有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

1 个答案:

答案 0 :(得分:0)

input.shape [1、58、8、8]对应于以下内容:

  • 1是批处理大小。 More on batchsize
  • 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>