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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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