ValueError: 参数`target`和`output`必须具有相同的形状。接收到:target.shape=(None, 512), output.shape=(None, 3)

我试图训练一个BERT模型来解决多分类问题。

在运行以下代码时,我遇到了这个错误:

Arguments `target` and `output` must have the same shape. Received: target.shape=(None, 512), output.shape=(None, 3)
import tensorflow as tf
epochs = 4
train_dataloader = train_dataset.shuffle(buffer_size=10000).batch(batch_size)
validation_dataloader = val_dataset.batch(batch_size)
# 开始训练
history = model.fit(
    train_dataloader,  # 训练数据
    validation_data=validation_dataloader,  # 验证数据
    epochs=epochs, 
    verbose=1
)
# 保存模型
model.save("bert_model.h5")

这是一个测试:

for batch in train_dataloader.take(1):
    input_ids, attention_masks, labels = batch
    print("批次 input_ids 形状:", input_ids.shape)
    print("批次 attention_masks 形状:", attention_masks.shape)
    print("批次 labels 形状:", labels.shape)
# 我得到了以下输出
Batch input_ids shape: (16, 512)
Batch attention_masks shape: (16, 512)
Batch labels shape: (16,)

我已经检查了张量的形状。


回答:

你的标签形状为(16,),而你的模型输出形状为(None,3)。

问题可能在于你的标签没有进行独热编码。它们应该与你的输出层具有相同的第二维度:

from tensorflow.keras.utils import to_categorical
num_classes = 3
labels = to_categorical(labels, num_classes=num_classes)
print(labels.shape)

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注