训练期间出现错误:新值和先前值的形状必须匹配

Getting Error during training: shape of the new value and previous value must match

我在 Tensorflow.js 中训练新模型时遇到了这个错误。这是一种在 TypeScript 中重现它的方法:

import * as tf from '@tensorflow/tfjs-node';

const run = async () => {
  const optimizer = tf.train.adam(0.001);

  const input1 = tf.input({
    shape: [ 2 ]
  });
  const out1 = tf.layers.dense({
    units: 1,
    name: 'out1',
    activation: 'tanh'
  }).apply(input1) as tf.SymbolicTensor;
  const model1 = tf.model(
    {
      inputs: input1,
      outputs: out1
    }
  );
  model1.compile(
    {
      optimizer,
      loss: 'meanSquaredError'
    }
  );
  await model1.fit(tf.ones([8, 2]), tf.ones([8, 1]), {
    batchSize: 4,
    epochs: 1
  });

  const input2 = tf.input({
    shape: [ 2 ]
  });
  const out2 = tf.layers.dense({
    units: 2,
    name: 'out2',
    activation: 'tanh'
  }).apply(input2) as tf.SymbolicTensor;
  const model2 = tf.model(
    {
      inputs: input2,
      outputs: out2
    }
  );
  model2.compile(
    {
      optimizer,
      loss: 'meanSquaredError'
    }
  );
  await model2.fit(tf.ones([8, 2]), tf.ones([8, 2]), {
    batchSize: 4,
    epochs: 1
  });
};

run();

当第二个模型开始训练时显示此错误:错误:新值 (2,2) 和先前值 (2,1) 的形状必须匹配

虽然两个模型都已正确定义,但错误是由于同一优化器实例造成的。

为防止出现此错误,您应该分别实例化每个优化器:

model1.compile(
  {
    optimizer: tf.train.adam(0.001),
    loss: 'meanSquaredError'
  }
);

model2.compile(
  {
    optimizer: tf.train.adam(0.001),
    loss: 'meanSquaredError'
  }
);