拟合 tensorflow2 模型时精度不兼容的形状

Incompatible shapes for Accuracy when fitting tensorflow2 model

我是 运行 Tensorfow 2.0.0-alpha0 上的文本生成模型 (RNN),尽管我在拟合模型时得到了损失指标,但在插入精度时出现以下错误:

InvalidArgumentError: Incompatible shapes: [64] vs. [64,200]
[[{{node metrics_4/accuracy/Equal}}]] [Op:__inference_keras_scratch_graph_6491]

我尝试手动定义单个批次(训练前)的准确性:

def loss(labels, logits):
    return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)
def accuracy(labels, logits):
    return tf.keras.metrics.sparse_categorical_accuracy(labels,l ogits)

example_batch_loss  = loss(target_example_batch, example_batch_predictions)
example_batch_acc  = accuracy(target_example_batch, example_batch_predictions)
print("Prediction shape: ", example_batch_predictions.shape, " # (batch_size, sequence_length, vocab_size)")
print("Loss:      ", example_batch_loss.numpy().mean())
print("Accuracy:      ", example_batch_acc.numpy().mean())

输出是:

Prediction shape: (64, 200, 34) # (batch_size, sequence_length, vocab_size) Loss: 3.5263805 Accuracy: 0.01265625

然后我跟着:

optimizer = tf.keras.optimizers.RMSprop(lr=lr) 
model.compile(optimizer=optimizer, loss=loss, metrics =['accuracy']) 
history = model.fit(dataset, epochs=epochs, callbacks[checkpoint_callback]) 

并得到上面提到的错误(损失工作正常)。如果我在编译中尝试 "accuracy = accuracy",我会得到:

raise ValueError('Session keyword arguments are not support during eager execution. You passed: %s' % (kwargs,))

有什么想法/建议吗?

accuracy 不是 Model.fit 的标准参数 - 它将在 **kwargs 下被接受,然后将以图形模式传递给 session.run。试试 metrics=[accuracy].