1

我正在尝试在 tensorflow.js 中微调 CNN。为此,我想在预训练模型的最后一层添加一个头部。python tensorflow 中的等效代码如下,我们在预训练的效率网络中添加了一个平均池化层。

import tensorflow as tf

img_base = tf.keras.applications.efficientnet.EfficientNetB0(include_top=False, weights='imagenet')
img_base = tf.keras.layers.GlobalAveragePooling2D()(img_base.output)

但是,JavaScript 中的相同代码会导致错误。

const tf = require('@tensorflow/tfjs-node');

const getModel = async function () {
    const imgBase = await tf.loadLayersModel('file://./tfjs_models/efficientnetb0_applications_notop/model.json');
    const imgPoolLayer = tf.layers.globalAveragePooling2d({dataFormat: 'channelsLast'});
    const imgPool = imgPoolLayer.apply(imgBase.outputs);
}
Error: Arguments to apply() must be all SymbolicTensors or all Tensors
    at new ValueError (/home/stanleyzheng/kds/kds-melanoma/tfjs_scripts/node_modules/@tensorflow/tfjs-layers/dist/tf-layers.node.js:16792:28)
    at Concatenate.Layer.apply (/home/stanleyzheng/kds/kds-melanoma/tfjs_scripts/node_modules/@tensorflow/tfjs-layers/dist/tf-layers.node.js:19983:19)
    at getModel (/home/stanleyzheng/kds/kds-melanoma/tfjs_scripts/train.js:32:29)

打印imgBase.outputs给我们以下结果。imgBase.outputs[0]返回与上述相同的错误。

[
  SymbolicTensor {
    dtype: 'float32',
    shape: [ null, 1280, 7, 7 ],
    sourceLayer: Activation {
      _callHook: null,
      _addedWeightNames: [],
      _stateful: false,
      id: 236,
      activityRegularizer: null,
      inputSpec: null,
      supportsMasking: true,
      _trainableWeights: [],
      _nonTrainableWeights: [],
      _losses: [],
      _updates: [],
      _built: true,
      inboundNodes: [Array],
      outboundNodes: [],
      name: 'top_activation',
      trainable_: true,
      initialWeights: null,
      _refCount: 1,
      fastWeightInitDuringBuild: true,
      activation: Swish {}
    },
    inputs: [ [SymbolicTensor] ],
    callArgs: {},
    outputTensorIndex: undefined,
    id: 548,
    originalName: 'top_activation/top_activation',
    name: 'top_activation/top_activation',
    rank: 4,
    nodeIndex: 0,
    tensorIndex: 0
  }
]

我们如何获得基础模型的输出,以便将其输入到单独的层中?谢谢。

4

1 回答 1

0

好吧,事实证明,用一个最小的例子,它是有效的。model.outputs简单地输入layer.apply()作品。

const tf = require(@tensorflow/tfjs)

const getModel = async function () {
    const baseModel = await tf.sequential();
    baseModel.add(tf.layers.conv2d({inputShape: [28, 28, 1], kernelSize: 5, filters: 8, strides: 1, activation: 'relu'}))
    let imgPoolLayer = tf.layers.globalAveragePooling2d({dataFormat: 'channelsLast'});
    let imgPool = imgPoolLayer.apply(baseModel.outputs);
}
getModel()
于 2021-07-12T19:20:49.707 回答