TypeError: ‘NoneType’ 对象不可调用

huangapple go评论211阅读模式
英文:

Load accuracy metric with evaluate ,sometime mistakes happen: TypeError: 'NoneType' object is not callable

问题

这是代码中的错误原因:

  1. TypeError: 'NoneType' object is not callable

这个错误通常表示您尝试调用一个NoneType对象,但它不可调用。在您的代码中,这个错误发生在以下行:

  1. accuracy = evaluate.load("accuracy")

这里的 evaluate.load("accuracy") 返回了一个NoneType对象,而您尝试将其赋值给 accuracy 变量,然后尝试调用它,但 NoneType 对象不支持调用。

要解决这个问题,您可以检查 evaluate.load("accuracy") 返回的内容,确保它是一个可调用的函数或对象。您还可以查看 evaluate 模块的文档或源代码,以确保您正确地加载了评估器对象。

如果您需要更具体的帮助,需要查看 evaluate 模块的相关文档或提供更多代码上下文。

英文:

I'm using Bert and other encoder models for text classification tasks,but when I try to load accuracy metric with evaluate in huggingface,sometime mistakes happen: TypeError: 'NoneType' object is not callable.
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this. Thanks in advance.

This is the cause of the code error:

  1. ─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮
  2. /home/ubuntu/Bill_PyCharm/absa-three/yasi_encoder/yasi_roberta.py:94 in <module>
  3. 91 test_dataset = datasets.Dataset.from_dict(train_ds.get_dataset())
  4. 92
  5. 93 """## Train Loop"""
  6. 94 accuracy = evaluate.load("accuracy")
  7. 95 # accuracy = evaluate.load("../evaluate/accuracy.py") │
  8. 96 # recall = evaluate.load("recall") │
  9. 97 # precision = evaluate.load("precision") │
  10. /home/ubuntu/anaconda3/lib/python3.9/site-packages/evaluate/loading.py:778 in load
  11. 775 path, module_type=module_type, revision=revision, download_config=download_confi
  12. 776 ).module_path
  13. 777 evaluation_cls = import_main_class(evaluation_module)
  14. 778 evaluation_instance = evaluation_cls(
  15. 779 config_name=config_name,
  16. 780 process_id=process_id,
  17. 781 num_process=num_process,
  18. ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
  19. TypeError: 'NoneType' object is not callable

This is the source code:

  1. """# Loading the Libraries & Models"""
  2. import pandas as pd`enter code here`
  3. import numpy as np
  4. import evaluate
  5. import torch
  6. from datasets import Dataset
  7. import datasets
  8. from torch.utils.data import Dataset
  9. from transformers import (AutoTokenizer,
  10. AutoModelForSequenceClassification,
  11. TrainingArguments,
  12. Trainer)
  13. device = 'cuda' if torch.cuda.is_available() else 'cpu'
  14. print(f"Device: {device}")
  15. check_point = "xlm-roberta-base"
  16. # check_point = "hfl/chinese-roberta-wwm-ext"
  17. output_dir = "./models/yasi/" + check_point
  18. tokenizer = AutoTokenizer.from_pretrained(check_point)
  19. model = AutoModelForSequenceClassification.from_pretrained(check_point, num_labels=2).to(device)
  20. import pandas as pd
  21. from datasets import Dataset
  22. from sklearn.model_selection import train_test_split
  23. import json
  24. # 读取配置文件
  25. config_file = '../HyperParameter/config.json'
  26. with open(config_file, 'r') as f:
  27. config = json.load(f)
  28. # 从配置中获取需要的值
  29. batch_size = config['batch_size']
  30. dataset = config['dataset']
  31. epoch = config['epoch']
  32. # 读取数据集
  33. data = pd.read_csv(dataset, sep='\t') # from datasets import Dataset
  34. # 随机划分数据集
  35. train_data, remaining_data = train_test_split(data, test_size=0.2, random_state=42)
  36. dev_data, test_data = train_test_split(remaining_data, test_size=0.5, random_state=42)
  37. # 将划分后的数据集转换为Dataset对象
  38. train_df = Dataset.from_pandas(train_data)
  39. dev_df = Dataset.from_pandas(dev_data)
  40. test_df = Dataset.from_pandas(test_data)
  41. class YasiDataset(Dataset):
  42. def __init__(self, df, tokenizer: AutoTokenizer):
  43. super(YasiDataset).__init__()
  44. self.sentence = []
  45. self.labels = []
  46. # 读取每一行内容
  47. for row in df:
  48. # 提取content列的内容(假设是第二列)
  49. content = row["sentence"]
  50. labels = row["label"]
  51. # 将content添加到sentence_pairs列表中
  52. self.sentence.append(content)
  53. self.labels.append(labels)
  54. self.labels = torch.tensor(self.labels)
  55. self.tokenizer_output = tokenizer(self.sentence,
  56. padding=True,
  57. truncation=True,
  58. max_length=512, # 最大长度
  59. return_tensors='pt',
  60. return_token_type_ids=True,
  61. return_attention_mask=True,
  62. )
  63. self.tokenizer_output['labels'] = self.labels
  64. def __len__(self):
  65. return len(self.tokenizer_output.shape[0])
  66. def get_dataset(self):
  67. return self.tokenizer_output
  68. train_ds = YasiDataset(train_df, tokenizer)
  69. dev_ds = YasiDataset(dev_df, tokenizer)
  70. test_ds = YasiDataset(test_df, tokenizer)
  71. train_dataset = datasets.Dataset.from_dict(train_ds.get_dataset())
  72. dev_dataset = datasets.Dataset.from_dict(dev_ds.get_dataset())
  73. test_dataset = datasets.Dataset.from_dict(test_ds.get_dataset())
  74. """## Train Loop"""
  75. accuracy = evaluate.load("accuracy")

I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.

答案1

得分: 1

现在,我发现了这个问题的问题所在。我的计算机上的评估版本是0.1.2,我们应该更新评估的版本。
使用以下代码:
pip install --upgrade evaluate

英文:

now,I find what's wrong with this problem.the evaluate version of my computer is evaluate 0.1.2. we should update the version of the evaluate.
use the code as follow:
pip install --upgrade evaluate

huangapple
  • 本文由 发表于 2023年7月6日 11:11:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625249.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定