You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从列表创建Hugging Face Dataset?解决AttributeError问题

自定义Hugging Face Dataset子类报错AttributeError的解决方案

你尝试将列表转换为Hugging Face Dataset用于模型训练,通过继承Dataset类自定义数据集时,出现AttributeError: can't set attribute错误,以下是具体解决方案:

问题根源

Dataset类的data属性是只读的,无法直接赋值;且该类初始化必须传入Arrow Table对象,不能像普通类那样自定义__init__方法直接处理列表数据。


方案1:正确继承Dataset类

如果必须自定义子类,需先将列表转换为Arrow Table,再传给父类初始化:

from datasets import Dataset
import pyarrow as pa
import torch

class MkqaChineseDataset(Dataset):
    def __init__(self, data):
        # 将列表数据转换为Arrow Table
        arrow_table = pa.Table.from_pylist(data)
        # 调用父类的初始化方法
        super().__init__(arrow_table)
    
    def __getitem__(self, idx):
        sample = super().__getitem__(idx)
        # 补充labels字段
        return {
            "input_ids": sample["input_ids"], 
            "attention_mask": sample["attention_mask"],
            "labels": sample["input_ids"]
        }

buffer_test = [
    {'input_ids': torch.Tensor([9437,29,210]), 'attention_mask': torch.Tensor([1, 1, 1])},
    {'input_ids': torch.Tensor([37,9,211]), 'attention_mask':  torch.Tensor([1, 1, 1])},
    {'input_ids': torch.Tensor([937,19,212]), 'attention_mask': torch.Tensor([1, 1, 1])}
]

mkqa = MkqaChineseDataset(buffer_test)
print(isinstance(mkqa, Dataset))  # 输出True

方案2:直接创建Dataset(更推荐)

Hugging Face Dataset支持直接从列表、字典等结构创建,无需自定义子类,操作更简洁:

from datasets import Dataset
import torch

buffer_test = [
    {'input_ids': torch.Tensor([9437,29,210]), 'attention_mask': torch.Tensor([1, 1, 1])},
    {'input_ids': torch.Tensor([37,9,211]), 'attention_mask':  torch.Tensor([1, 1, 1])},
    {'input_ids': torch.Tensor([937,19,212]), 'attention_mask': torch.Tensor([1, 1, 1])}
]

# 直接从列表生成Dataset
mkqa = Dataset.from_list(buffer_test)
# 通过map方法添加labels字段
mkqa = mkqa.map(lambda x: {"labels": x["input_ids"]})

print(isinstance(mkqa, Dataset))  # 输出True

内容的提问来源于stack exchange,提问作者4daJKong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:53:17