English 中文(简体)
履历: 创建型长但预期的Float在使用APIC培训师进行微调时
原标题:RuntimeError: Found dtype Long but expected Float when fine-tuning using Trainer API

我试图将BERT模型与Huggingface 培训员APIC进行情感分析(将案文归类为积极/否定性)。 我的数据集有两栏:<代码>Text和Sentiment

Text                     Sentiment
This was good place          1
This was bad place           0

我的守则是:

from datasets import load_dataset
from datasets import load_dataset_builder
from datasets import Dataset
import datasets
import transformers
from transformers import TrainingArguments
from transformers import Trainer

dataset = load_dataset( csv , data_files= ./train/test.csv , sep= ; )
tokenizer = transformers.BertTokenizer.from_pretrained("TurkuNLP/bert-base-finnish-cased-v1")
model = transformers.BertForSequenceClassification.from_pretrained("TurkuNLP/bert-base-finnish-cased-v1", num_labels=1) 
def tokenize_function(examples):
    return tokenizer(examples["Text"], truncation=True, padding= max_length )

tokenized_datasets = dataset.map(tokenize_function, batched=True)
tokenized_datasets = tokenized_datasets.rename_column( Sentiment ,  label )
tokenized_datasets = tokenized_datasets.remove_columns( Text )
training_args = TrainingArguments("test_trainer")
trainer = Trainer(
    model=model, args=training_args, train_dataset=tokenized_datasets[ train ]
)
trainer.train()

Running this throws error:

Variable._execution_engine.run_backward(
RuntimeError: Found dtype Long but expected Float

错误可能来自数据集本身,但我能否用我的代码加以确定? 我搜索了因特网,这一错误似乎以前通过“把帐篷推向漂浮”来解决,但我如何与Amper培训员打交道? 任何建议都受到高度赞赏。

参考:

https://discuss.pytorch.org/t/run-back-expected-dtype-float-but-got-d-type-long/61650/10

问题回答

在此,我假定,你试图做一个标签分类,即预测一个结果,而不是预测多重结果。

但是,损失功能(我不知道你正在使用什么,但很可能是BCE)是你使用的,希望你把病媒作为标签。

因此,你们要么需要按照评论中所建议的人把你的标签转换为病媒,要么你可以把损失功能改为跨热带损失,把你标签参数的编号改为2(或不管怎样)。 这两种解决办法都将奏效。

If you want to train your model as multi-label classifier you can convert your labels to vectors with using sklearn.preprocessing:

from sklearn.preprocessing import OneHotEncoder
import pandas as pd
import numpy as np

dataset = pd.read_csv("filename.csv", encoding="utf-8")
enc_labels = preprocessing.LabelEncoder()
int_encoded = enc_labels.fit_transform(np.array(dataset["Sentiment"].to_list()))

onehot_encoder = OneHotEncoder(sparse = False)
int_encoded = int_encoded.reshape(len(int_encoded),1)
onehot_encoded = onehot_encoder.fit_transform(int_encoded)
for index, cat in dataset.iterrows():
    dataset.at[index ,  Sentiment ] = onehot_encoded[index]

你可以提供你的数据。

如果您在Pandas 格式。 你可以做到:

df[ column_name ] = df[ column_name ].astype(float)

如果你在HuggingFace格式。 你应该做这样的事情:

from datasets import load_dataset
dataset = load_dataset( glue ,  mrpc , split= train )
from datasets import Value, ClassLabel

new_features = dataset.features.copy()
new_features["idx"] = Value( int64 )
new_features["label"] = ClassLabel(names=[ negative ,  positive ])
new_features["idx"] = Value( int64 )
dataset = dataset.cast(new_features)

此前:

dataset.features
{ idx : Value(dtype= int32 , id=None),
  label : ClassLabel(num_classes=2, names=[ not_equivalent ,  equivalent ], id=None),
  sentence1 : Value(dtype= string , id=None),
  sentence2 : Value(dtype= string , id=None)}

After:

dataset.features
{ idx : Value(dtype= int64 , id=None),
  label : ClassLabel(num_classes=2, names=[ negative ,  positive ], id=None),
  sentence1 : Value(dtype= string , id=None),
  sentence2 : Value(dtype= string , id=None)}

分类模式按违约情况与num_labels进行双重分类。 <代码>None。 <num_labels to 1 这使它成为一个倒退的问题,因此你正在经历错误。 页: 1





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签