1.2 Kaggle大白话:Eedi竞赛Transformer框架解决方案02-GPT_4o生成训练集缺失数据

目录

    • 0. 本栏目竞赛汇总表
    • 1. 本文主旨
    • 2. AI工程架构
    • 3. 数据预处理模块
      • 3.1 配置数据路径和处理参数
      • 3.2 配置API参数
      • 3.3 配置输出路径
    • 4. AI并行处理模块
      • 4.1 定义LLM客户端类
      • 4.2 定义数据处理函数
      • 4.3 定义JSON保存函数
      • 4.4 定义数据分片函数
      • 4.5 定义分片处理函数
      • 4.5 定义文件名排序函数
    • 5. 数据整合模块
      • 5.1 加载数据并生成分片
      • 5.2 初始化LLM客户端并测试
      • 5.3 并行处理数据生成
      • 5.4 合并处理结果
      • 5.5 保存最终结果

0. 本栏目竞赛汇总表

Kaggle竞赛汇总

1. 本文主旨

  • 大白话:由于在上一篇文章的数据探索中,我们发现了部分训练数据的错误解释存在缺失,因此直接使用GPT_4o+人设提示词工程,对训练集数据存在的错误解释缺失问题的处理。
  • 通过本文可收获技能:API调用AI接口、人设提示词工程案例、复杂的数据处理与缓存处理。
  • 上文回顾:Eedi大模型蒸馏方案01-竞赛信息解读与数据理解

2. AI工程架构

数据整合模块
初始化客户端
加载数据
并行处理生成
合并结果
保存CSV
AI并行处理模块
定义数据处理函数
定义LLM客户端
定义JSON保存函数
定义分片函数
定义排序函数
数据预处理模块
配置路径和参数
导入依赖库
配置API和输出

3. 数据预处理模块

3.1 配置数据路径和处理参数

data_path = "~/work/eedi_synthetic_data/MalAlgoQA_format.csv"
index_start = 0
index_end = len(df)
step = 100
max_workers = 2

3.2 配置API参数

model_config = dict(openai_api_base = "https://testshellapi.kimi.asia/v1", api_key = "****",model = "gpt-4o",default_system_prompt = """##TaskYou are a Mathematics teacher. Your task is to reason and identify the ConstructName and SubjectName and then the misconception behind the user input Incorrect Answers with the Question.ConstructName is Most granular level of knowledge related to question, appears to describe the specific mathematical method or procedure used to solve the question. It explains the technique or approach needed to reach the answer.SubjectName is More general context than the construct, represents the broader mathematical topic or category that the question belongs to.Misconceptions are a mistake in conceptual understanding and they have relations with all the applications of those concepts. For example, a single misconception on the connections among proportional relationships (part/whole, part/part, whole/part) can cause problems in identifying those patterns in drawings and can be the cause of failing to realize all parts must be of equal size, therefore associating the denominator of the fraction with the total number of parts regardless their size.Answer concisely what misconception it is to lead to getting the incorrect answer.Do not use "The misconception is" to start your answers.Do not mention the concrete details of the question or answers. ##User inputQuestion: The question textA: multiple choice answer A textB: multiple choice answer B textC: multiple choice answer C textD: multiple choice answer D textCorrect Answer: The correct answer text##You should answer in the following JSON format{"ConstructName": "here writes the constructName","SubjectName": "here writes the SubjectName""MisconceptionAName": "here writes the answer A's misconception.","MisconceptionBName": "here writes the answer B's misconception.","MisconceptionCName": "here writes the answer C's misconception.","MisconceptionDName": "here writes the answer D's misconception.",}""", # system prompt,default_temperature = 0.5,max_tokens = 256,
)

3.3 配置输出路径

cache_folder = f"./cache_{model_config['model']}_model_misconceptions_result"
if not os.path.exists(cache_folder):os.makedirs(cache_folder)
output_data_path = f"misconception_data_{os.path.splitext(os.path.basename(data_path))[0]}_{model_config['model']}.csv"

4. AI并行处理模块

4.1 定义LLM客户端类

class LLMChat:def __init__(self, openai_api_base, api_key, model, default_temperature, default_system_prompt, max_tokens=512):self.client = OpenAI(api_key = api_key,base_url=openai_api_base,)self.model = modelself.default_temperature = default_temperatureself.default_system_prompt = default_system_promptself.max_tokens = max_tokensdef chat(self, user_prompt, system_prompt=None, temperature=None):if not system_prompt:system_prompt = self.default_system_promptif not temperature:temperature = self.default_temperaturechat_response = self.client.chat.completions.create(model=self.model,temperature=temperature,messages=[{"role": "system", "content": system_prompt},{"role": "user", "content": user_prompt},],max_tokens=self.max_tokens,response_format={"type": "json_object"})return chat_response.choices[0].message.content

4.2 定义数据处理函数

def process_row(args, debug=False):user_prompt = """Question: {question}A: {answer_a}B: {answer_b}C: {answer_c}D: {answer_d}Correct Answer: {correct_answer}"""index, row = argsca = row["CorrectAnswer"]correctanswer = row[f"Answer{ca}Text"]input_user_prompt = user_prompt.format(question=row['QuestionText'],answer_a=row['AnswerAText'],answer_b=row['AnswerBText'],answer_c=row['AnswerCText'],answer_d=row['AnswerDText'],correct_answer=correctanswer,)ret_data = {}try:ret_data = vc.chat(input_user_prompt)if debug:print(ret_data+'\n')except Exception as e:print(f'An exception occur {str(e)}')ret_data['error'] = str(e)passif debug:print('system: ', model_config['default_system_prompt'])print('>'* 50)print('user_input: ', input_user_prompt)print('>'* 50)print('assistant: ', ret_data)return ret_data

4.3 定义JSON保存函数

def save_json(fn, obj):with open(fn, 'w') as f:json.dump(obj, f, ensure_ascii=False, indent=4)print(f"save file to {fn}")

4.4 定义数据分片函数

def slice_range(start, end, step):if step <= 0:raise ValueError("步长必须大于0")result = []while start <= end:result.append(start)start += stepif result[-1] < end:result.append(end)return result

4.5 定义分片处理函数

def process_pairs(sliced_range):slices = []for first, second in zip(sliced_range, sliced_range[1:]):slices.append([first, second])return slices

4.5 定义文件名排序函数

def natural_sort_key(filename):parts = re.findall(r'\d+', filename)return tuple(map(int, parts))

5. 数据整合模块

5.1 加载数据并生成分片

df = pd.read_csv(data_path)
df.head()
sliced_range = process_pairs(slice_range(index_start, index_end, step))

df数据检查:
在这里插入图片描述

5.2 初始化LLM客户端并测试

vc = LLMChat(**model_config)
r = process_row((7, df.iloc[7]), debug=True)

5.3 并行处理数据生成

for slices in tqdm(sliced_range, total=len(sliced_range)):output_filepath = f'{cache_folder}/cache_res_{slices[0]}.json'if os.path.exists(output_filepath):print(f'cache file exists, skip {output_filepath}')continuedf_tasks = df.iloc[slices[0]:slices[1]]results = []with ProcessPoolExecutor(max_workers=max_workers) as executor:results = list(tqdm(executor.map(process_row, df_tasks.iterrows()), total=len(df_tasks)))save_json(output_filepath, results)

5.4 合并处理结果

f_names = glob.glob(f'{cache_folder}/*.json')
sorted_filenames = sorted(f_names, key=natural_sort_key)
f_names = sorted_filenamesresults = []
for fn in f_names:with open(fn, 'r') as f:batch_results = json.load(f)results.extend(batch_results)l = len(results)
results = [json.loads(r) for r in results]

5.5 保存最终结果

df = df.iloc[:l]
gen_df = pd.DataFrame(results)
df = pd.concat([df, gen_df], axis=1)
df.to_csv(output_data_path, index=False)

(To be continued)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/70885.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

pycharm远程连接服务器运行pytorch

Linux部署pytorch 背景介绍 不同的开源代码可能需要不同的实验环境和版本&#xff0c;这时候的确体现出Anaconda管理环境的好处了&#xff0c;分别搞一个独立环境方便管理。 有的教程建议选择较旧的版本&#xff0c;但笔者建议在条件允许的情况下安装最新版&#xff0c;本次…

Python开发 Flask框架面试题及参考答案

目录 Flask 的核心设计理念是什么?与 Django 相比有哪些显著差异? 解释 Flask 框架的核心理念及其作为 “微框架” 的优缺点 Flask 的依赖库有哪些?简述 Werkzeug 和 Jinja2 的作用 什么是 WSGI?Flask 如何基于 WSGI 实现服务端与应用的交互 解释 RESTful API 的设计原…

从“Switch-case“到“智能模式“:C#模式匹配的终极进化指南

当代码开始"思考" 你是否厌倦了层层嵌套的if-else地狱&#xff1f;是否想过让代码像侦探推理一样优雅地解构数据&#xff1f;C#的模式匹配正是这样一把瑞士军刀&#xff0c;从C# 7.0到C# 12&#xff0c;它已悄然进化成改变编程范式的利器。 一、模式匹配的三重境界…

组件注册方式、传递数据

组件注册 一个vue组件要先被注册&#xff0c;这样vue才能在渲染模版时找到其对应的实现。有两种注册方式&#xff1a;全局注册和局部注册。&#xff08;组件的引入方式&#xff09; 以下这种属于局部引用。 组件传递数据 注意&#xff1a;props传递数据&#xff0c;只能从父…

ROS的action通信——实现阶乘运算(三)

在ROS中除了常见的话题(topic&#xff09;通信、服务(server)通信等方式&#xff0c;还有action通信这一方式&#xff0c;由于可以实时反馈任务完成情况&#xff0c;该通信方式被广泛运用于机器人导航等任务中。本文将通过三个小节的分享&#xff0c;实现基于action通信的阶乘运…

四款 AI 协作办公工具,AI工具库革新办公效率

在数字化办公时代&#xff0c;AI 技术正深刻改变着我们的工作方式。AIDH.NETAI工具库汇聚了众多先进的工具&#xff0c;今天我们来了解 AI协作办公工具&#xff0c;探索它们如何助力企业和团队在办公场景中脱颖而出。 Taskade&#xff1a;智能工作流的领航者 Taskade 是一款将…

vue2 h5 画高德地图电子围栏

使用前请先申请高德地图key JavaScript API | 腾讯位置服务 npm install lodash-es效果图 子组件代码 <template><div class"fence-container"><div v-if"loading" class"map-loading"><div class"loader">…

unity学习54:图片+精灵+遮罩mask,旧版文本 text 和新的TMP文本

目录 1 图片 image 1.1 如果直接导入image 1.2 图片 image 和精灵 sprite 1.2.1 继续修改上面的格式 texture type 是default 1.2.2 再次关联到UI的 image 物体上就可以了 1.3 图片和遮罩 mask 1.3.1 创建1个父物体和1个子物体&#xff0c;分别都是image 1.3.2 如果父…

Spring Data JPA vs MyBatis:ORM框架如何选择?

在选择ORM框架时&#xff0c;Spring Data JPA和MyBatis是两个常见的选择&#xff0c;它们各有优缺点&#xff0c;适用于不同的场景。以下是两者的对比&#xff0c;帮助你做出选择&#xff1a; 1. Spring Data JPA 优点&#xff1a; 开发效率高&#xff1a;通过简单的接口定义和…

Selenium 与 Coze 集成

涵盖两者的基本概念、集成步骤、代码示例以及相关注意事项。 基本概念 Selenium:是一个用于自动化浏览器操作的工具集,支持多种浏览器(如 Chrome、Firefox 等),能够模拟用户在浏览器中的各种操作,如点击、输入文本、选择下拉框等,常用于 Web 应用的自动化测试。Coze:它…

在线骑行|基于SpringBoot的在线骑行网站设计与实现(源码+数据库+文档)

在线骑行网站系统 目录 基于SpringBoot的在线骑行设计与实现 一、前言 二、系统设计 三、系统功能设计 5.1用户信息管理 5.2 路线攻略管理 5.3路线类型管理 5.4新闻赛事管理 四、数据库设计 五、核心代码 六、论文参考 七、最新计算机毕设选题推荐 八、源码获取…

[深度学习]基于C++和onnxruntime部署yolov12的onnx模型

基于C和ONNX Runtime部署YOLOv12的ONNX模型&#xff0c;可以遵循以下步骤&#xff1a; 准备环境&#xff1a;首先&#xff0c;确保已经下载后指定版本opencv和onnruntime的C库。 模型转换&#xff1a; 安装好yolov12环境并将YOLOv12模型转换为ONNX格式。这通常涉及使用深度学习…

Imagination DXTP GPU IP:加速游戏AI应用,全天候畅玩无阻

日前&#xff0c;Imagination 推出了最新产品——Imagination DXTP GPU IP&#xff0c;在智能手机和其他功耗受限设备上加速图形和AI工作负载时&#xff0c;保证全天候的电池续航。它是我们最新D系列GPU的最终产品&#xff0c;集成了自2022年发布以来引入的一系列功能&#xff…

(python)Arrow库使时间处理变得更简单

前言 Arrow库并不是简单的二次开发,而是在datetime的基础上进行了扩展和增强。它通过提供更简洁的API、强大的时区支持、丰富的格式化和解析功能以及人性化的显示,填补了datetime在某些功能上的空白。如果你需要更高效、更人性化的日期时间处理方式,Arrow库是一个不错的选择…

pandas中的数据结构+数据查询

pandas 数据结构 Series Series是一种类似于一维数组的对象&#xff0c;它由一组数据&#xff08;不同数据类型&#xff09;以及一组与之相关的数据标签&#xff08;即索引&#xff09;组成。 列表创建 仅有数据列表即可产生最简单的Series s1 pd.Series([1,a,5.2,7]) 左侧…

使用前端 html css 和js 开发一个AI智能平台官网模板-前端静态页面项目

最近 AI 人工智能这么火&#xff0c;那必须针对AI 做一个 AI方面的 官方静态网站练手。让自己的前端技术更上一层楼&#xff0c;哈哈。 随着人工智能技术的不断发展&#xff0c;越来越多的AI应用开始渗透到各行各业&#xff0c;为不同领域的用户提供智能化解决方案。本网站致力…

React + TypeScript 数据模型驱动数据字典生成示例

React TypeScript 数据模型驱动数据字典生成示例 引言&#xff1a;数据字典的工程价值 在现代化全栈开发中&#xff0c;数据字典作为业务实体与数据存储的映射桥梁&#xff0c;直接影响系统可维护性与团队协作效率。传统手动维护字典的方式存在同步成本高和版本管理混乱两大痛…

MySQL八股整理

1. 如何定位慢查询&#xff1f; 慢查询一般发生在联表查询或者表中数据量较大时&#xff0c;当响应时间较长或者压测时间超过2s时&#xff0c;就认为是慢查询。定位慢查询的话一般有两种方法&#xff0c;一种是使用专门的分析工具去定位。另一种也是我们项目中之前使用过的方法…

ShardingSphere Proxy 配置

在使用 ShardingSphere Proxy 模式时&#xff0c;结合 主从复制架构 实现 读写分离&#xff0c;并按照 用户ID哈希算法 确定库、时间范围 确定表的场景下&#xff0c;配置文件需要做一些调整以支持分片、读写分离以及主从复制。 以下是如何配置 ShardingSphere Proxy 模式的详…

Redis集群机制及一个Redis架构演进实例

Replication&#xff08;主从复制&#xff09; Redis的replication机制允许slave从master那里通过网络传输拷贝到完整的数据备份&#xff0c;从而达到主从机制。为了实现主从复制&#xff0c;我们准备三个redis服务&#xff0c;依次命名为master&#xff0c;slave1&#xff0c;…