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

问题描述 投票:0回答:1

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

  • 我在运行下面的代码时遇到此错误

参数

target
output
必须具有相同的形状。收到:target.shape=(无,512),output.shape=(无,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)

# start training 
history = model.fit(
    train_dataloader,  # train_data
    validation_data=validation_dataloader,  # validation_data
    epochs=epochs,  
    verbose=1 
)
# save the model
model.save("bert_model.h5")
  • 这是一个测试
for batch in train_dataloader.take(1):
    input_ids, attention_masks, labels = batch
    print("Batch input_ids shape:", input_ids.shape) 
    print("Batch attention_masks shape:", attention_masks.shape) 
    print("Batch labels shape:", labels.shape)  

# I got this output
Batch input_ids shape: (16, 512)
Batch attention_masks shape: (16, 512)
Batch labels shape: (16,)

我已经检查过张量形状。 希望得到解答!

python tensorflow artificial-intelligence classification bert-language-model
1个回答
0
投票

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

问题可能是您的标签不是“one-hot 编码”。它们应该具有与输出层相同的第二维: from tensorflow.keras.utils import to_categorical num_classes = 3 labels = to_categorical(labels, num_classes=num_classes) print(labels.shape)

© www.soinside.com 2019 - 2024. All rights reserved.