处理Hugging Face上的数据集

当我们使用Hugging Face上的数据集时,有时候需要将数据集按照训练集、测试集、验证集的类别分别处理并写入不同的文件中,以便于我们在训练模型时能更好的处理数据。
下面这个方法就能很好的处理这个需求。

# 此方法适用于将huggingface的dataset类型的数据集写入jsonl格式的文件
# texts dataset['train']['text']
# labels dataset['train']['label']
# output_file 写入的文件路径
def makeupJsonlFile(texts, labels, output_file):
    prompt = " Question: What is the sentiment of the following text? Choose from 'positive' or 'negative'. Text: "
    sentences = []
    id2label = {
        '0': 'negative',
        '1': 'positive'
    }

    for index, sentence in enumerate(texts):
        sentence = prompt + sentence + ". Answer:"
        sentences.append(sentence)

    labels = [id2label[str(label)] for label in labels]

    print(f"Write into ... {output_file}")
    with open(output_file, "w", encoding='utf-8') as f_output:
        for sentence, label in zip(sentences, labels):
            data = {
                "text": sentence,
                "label": label
            }
            # 将数据字典转换为 JSON 格式并写入输出文件
            json.dump(data, f_output, ensure_ascii=False)
            f_output.write('\n')
暂无评论

发送评论 编辑评论


				
上一篇
下一篇