我试图训练一个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)