openAi 的API将交易数据归入预定义的类别中

本文探讨了对公共交易数据进行分类的三种方法:零样本分类、嵌入分类和微调分类。使用苏格兰图书馆的交易数据,通过替换模板进行初步预测,并计划通过训练和微调模型来提升分类效果。同时提到了Python中的相关库,如OpenAI、Pandas和Numpy等在处理和分析数据中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们将尝试将一个公共交易数据集分类为预定义的几个类别。这些方法应该适用于任何多类别分类的用例,其中我们试图将交易数据归入预定义的类别中,通过运行这个过程,您应该会得到一些处理已标记和未标记数据集的方法。

我们在本笔记本中采用的不同方法包括:

零样本分类:首先,我们将使用零样本分类来将交易放入五个命名桶中,仅使用提示进行指导。
嵌入分类:接下来,我们将在标记的数据集上创建嵌入,然后使用传统的分类模型来测试它们识别我们的类别的效果。
微调分类:最后,我们将在标记的数据集上训练一个微调模型,以查看它与零样本和少样本分类方法的比较。

  • 加载数据集
    我们将使用一份公共交易数据集,其中包含苏格兰图书馆超过25,000英镑的交易记录。数据集有三个特征,我们将使用它们:

供应商:供应商的名称
描述:交易的文本描述
价值:交易的价值,以英镑为单位

来源:https://data.nls.uk/data/organisational-data/transactions-over-25k/

我们将首先使用简单提示来评估基本模型在分类这些交易方面的表现。我们将为模型提供5个类别和一个“无法分类”的总类别,用于不能归类的交易。

import openai
import pandas as pd
import numpy as np
import json
import os

openai.api_key = os.getenv("OPENAI_API_KEY")
COMPLETIONS_MODEL = "text-davinci-002"
transactions = pd.read_csv('./data/25000_spend_dataset_current.csv', encoding= 'unicode_escape')

def request_completion(prompt):
    
    completion_response =   openai.Completion.create(
                            prompt=prompt,
                            temperature=0,
                            max_tokens=5,
                            top_p=1,
                            frequency_penalty=0,
                            presence_penalty=0,
                            model=COMPLETIONS_MODEL
                            )
        
    return completion_response

def classify_transaction(transaction,prompt):
    
    prompt = prompt.replace('SUPPLIER_NAME',transaction['Supplier'])
    prompt = prompt.replace('DESCRIPTION_TEXT',transaction['Description'])
    prompt = prompt.replace('TRANSACTION_VALUE',str(transaction['Transaction value (£)']))
    
    classification = request_completion(prompt)['choices'][0]['text'].replace('\n','')
    
    return classification


#这个函数使用Finetuning API中prepare_data函数的训练和验证输出,检查它们是否具有相同数量的类别。
#如果它们没有相同数量的类别,微调将失败并返回错误
def check_finetune_classes(train_file,valid_file):

    train_classes = set()
    valid_classes = set()
    with open(train_file, 'r') as json_file:
        json_list = list(json_file)
        print(len(json_list))

    for json_str in json_list:
        result = json.loads(json_str)
        train_classes.add(result['completion'])
        #print(f"result: {result['completion']}")
        #print(isinstance(result, dict))

    with open(valid_file, 'r') as json_file:
        json_list = list(json_file)
        print(len(json_list))

    for json_str in json_list:
        result = json.loads(json_str)
        valid_classes.add(result['completion'])
        #print(f"result: {result['completion']}")
        #print(isinstance(result, dict))
        
    if len(train_classes) == len(valid_classes):
        print('All good')
	else:
        print('Classes do not match, please prepare data again')


zero_shot_prompt = '''You are a data expert working for the National Library of Scotland. 
You are analysing all transactions over £25,000 in value and classifying them into one of five categories.
The five categories are Building Improvement, Literature & Archive, Utility Bills, Professional Services and Software/IT.
If you can't tell what it is, say Could not classify                      

Transaction:                      
Supplier: SUPPLIER_NAME
Description: DESCRIPTION_TEXT
Value: TRANSACTION_VALUE                      
The classification is:'''
#Get a test transaction
transaction = transactions.iloc[0]

# Interpolate the values into the prompt
prompt = zero_shot_prompt.replace('SUPPLIER_NAME',transaction['Supplier'])
prompt = prompt.replace('DESCRIPTION_TEXT',transaction['Description'])
prompt = prompt.replace('TRANSACTION_VALUE',str(transaction['Transaction value (£)']))

# Use our completion function to return a prediction
completion_response = request_completion(prompt)
print(completion_response['choices'][0]['text'])
test_transactions = transactions.iloc[:25]
test_transactions['Classification'] = test_transactions.apply(lambda x: classify_transaction(x,zero_shot_prompt),axis=1)

即使没有标记的样例,初始结果也相当不错!不能分类的那些交易是比较难的案例,没有明显的线索表明它们属于哪个类别,但是如果我们清理标记数据集并提供更多的示例,或许可以获得更好的性能。

RedisTimeSeries开源的时序数据数据库
BNF 语法描述
python将抽象语法树转换回源代码的工具库astor
Python 的抽象语法树库ast
python可以执行字符串形式的 Python 代码的库exec
python用于解析复杂文本数据的库Ply
python 用于解析复杂文本数据的库PyParsing
python用来进行代码语法高亮的库Pygments
Pylint
python处理网格数据的一个库GridDataFormats
python开发的开源数学软件系统SageMath
Python端到端的测试的生态系统库pyATS
Python 强大的模板引擎库 Skeleton BootStrap
python读取和编写配置文件库ConfigObj和ConfigParser
python在Web应用程序中安全地转义和渲染HTML的库MarkupSafe
Python为命令行界面(CLI)工具自动生成解析器的库Docopt
python的模板引擎库Mako,生成代码也很简单
python生成PDF文档的库reportlab
python的生成艺术字体的库pythonwordart
python生成和解决迷宫的库maze

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

openwin_top

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值