当前位置: 首页 > news >正文

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)

相关文章:

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 定义文件名排序…...

数据结构-顺序表专题

大家好&#xff01;这里是摆子&#xff0c;今天给大家带来的是C语言数据结构开端-顺序表专题&#xff0c;主要介绍了数据结构和动态顺序表的实现&#xff0c;快来看看吧&#xff01;记得一键三连哦&#xff01; 1.数据结构的概念 1.1什么是数据结构&#xff1f; 数据结构是计…...

docker和containerd从TLS harbor拉取镜像

私有镜像仓库配置了自签名证书&#xff0c;https访问&#xff0c;好处是不需要处理免费证书和付费证书带来的证书文件变更&#xff0c;证书文件变更后需要重启服务&#xff0c;自签名证书需要将一套客户端证书存放在/etc/docker/cert.d目录下&#xff0c;或者/etc/containerd/c…...

kafka-关于ISR-概述

一. 什么是ISR &#xff1f; Kafka 中通常每个分区都有多个副本&#xff0c;其中一个副本被选举为 Leader&#xff0c;其他副本为 Follower。ISR 是指与 Leader 副本保持同步的 Follower 副本集合。ISR 机制的核心是确保数据在多个副本之间的一致性和可靠性&#xff0c;同时在 …...

el-input实现金额输入

需求&#xff1a;想要实现一个输入金额的el-input&#xff0c;限制只能输入数字和一个小数点。失焦数字转千分位&#xff0c;聚焦转为数字&#xff0c;超过最大值&#xff0c;红字提示 效果图 失焦 聚焦 报错效果 // 组件limitDialog <template><el-dialog:visible.s…...

C++11智能指针

一、指针管理的困境 资源释放了&#xff0c;但指针没有置空&#xff08;野指针、指针悬挂、踩内存&#xff09; 没有释放资源&#xff0c;产生内存泄漏问题&#xff1b;重复释放资源&#xff0c;引发coredump 二、智能指针...

安装Git(小白也会装)

一、官网下载&#xff1a;Git 1.依次点击&#xff08;红框&#xff09; 不要安装在C盘了&#xff0c;要炸了&#xff01;&#xff01;&#xff01; 后面都 使用默认就好了&#xff0c;不用改&#xff0c;直接Next&#xff01; 直到这里&#xff0c;选第一个 这两种选项的区别如…...

驭势科技9周年:怀揣理想,踏浪前行

2025年的2月&#xff0c;驭势科技迎来9岁生日。位于国内外不同工作地的Uiseeker齐聚线上线下&#xff0c;共同庆祝驭势走过的璀璨九年。 驭势科技联合创始人、董事长兼CEO吴甘沙现场分享了驭势9年的奔赴之路&#xff0c;每一段故事都包含着坚持与拼搏。 左右滑动查看更多 Part.…...

一款在手机上制作电子表格

今天给大家分享一款在手机上制作电子表格的&#xff0c;免费好用的Exce1表格软件&#xff0c;让工作变得更加简单。 1 软件介绍 Exce1是一款手机制作表格的办公软件&#xff0c;您可以使用手机exce1在线制作表格、工资表、编辑xlsx和xls表格文件等&#xff0c;还可以学习使用…...

Python解决“比赛配对”问题

Python解决“比赛配对”问题 问题描述测试样例解决思路代码 问题描述 小R正在组织一个比赛&#xff0c;比赛中有 n 支队伍参赛。比赛遵循以下独特的赛制&#xff1a; 如果当前队伍数为 偶数&#xff0c;那么每支队伍都会与另一支队伍配对。总共进行 n / 2 场比赛&#xff0c;…...

【AI论文】RAD: 通过大规模基于3D图形仿真器的强化学习训练端到端驾驶策略

摘要&#xff1a;现有的端到端自动驾驶&#xff08;AD&#xff09;算法通常遵循模仿学习&#xff08;IL&#xff09;范式&#xff0c;但面临着因果混淆和开环差距等挑战。在本研究中&#xff0c;我们建立了一种基于3D图形仿真器&#xff08;3DGS&#xff09;的闭环强化学习&…...

Web开发:ORM框架之使用Freesql的导航属性

一、什么时候用导航属性 看数据库表的对应关系&#xff0c;一对多的时候用比较好&#xff0c;不用多写一个联表实体&#xff0c;而且查询高效 二、为实体配置导航属性 1.给关系是一的父表实体加上&#xff1a; [FreeSql.DataAnnotations.Navigate(nameof(子表.子表关联字段))]…...

【docker】namespace底层机制

Linux 的 Namespace 机制是实现容器化&#xff08;如 Docker、LXC 等&#xff09;的核心技术之一&#xff0c;它通过隔离系统资源&#xff08;如进程、网络、文件系统等&#xff09;为进程提供独立的运行环境。其底层机制涉及内核数据结构、系统调用和进程管理。以下是其核心实…...

【每天认识一个漏洞】url重定向

&#x1f31d;博客主页&#xff1a;菜鸟小羊 &#x1f496;专栏&#xff1a;Linux探索之旅 | 网络安全的神秘世界 | 专接本 | 每天学会一个渗透测试工具 常见应用场景 主要是业务逻辑中需要进行跳转的地方。比如登录处、注册处、访问用户信息、订单信息、加入购物车、分享、收…...

端口映射/内网穿透方式及问题解决:warning: remote port forwarding failed for listen port

文章目录 需求&#xff1a;A机器是内网机器&#xff0c;B机器是公网服务器&#xff0c;想要从公网&#xff0c;访问A机器的端口方式&#xff1a;端口映射&#xff0c;内网穿透&#xff0c;使用ssh打洞端口&#xff1a;遇到问题&#xff1a;命令执行成功&#xff0c;但是端口转发…...

Polardb开发者大会

这是第二次参加这个大会 还有不少老朋友 好多年没有这种经历了–大会讲的我不是很懂 10几年前参会&#xff0c;那时候自己不懂。后来就慢慢懂了。这些年参会都虽然还在不断学习&#xff0c;但是没觉得自己差距很大了。 这次出来很不一样&#xff0c;一堆新的技能&#xff0c;这…...

从二维随机变量到多维随机变量

二维随机变量 设 X X X和 Y Y Y是定义在同一样本空间 Ω \varOmega Ω上的两个随机变量&#xff0c;称由它们组成的向量 ( X , Y ) (X, Y) (X,Y)为二维随机变量&#xff0c;亦称为二维随机向量&#xff0c;其中称 X X X和 Y Y Y是二维随机变量的分量。 采用多个随机变量去描述…...

Vulnhub靶场 Kioptrix: Level 1.3 (#4) 练习

目录 0x00 环境准备0x01 主机信息收集0x02 站点信息收集0x03 漏洞查找与利用0x04 总结 0x00 环境准备 下载&#xff1a;https://download.vulnhub.com/kioptrix/Kioptrix4_vmware.rar 解压后得到的是vmdk文件。在vm中新建虚拟机&#xff0c;稍后安装操作系统&#xff0c;系统选…...

权重生成图像

简介 前面提到的许多生成模型都有保存了生成器的权重,本章主要介绍如何使用训练好的权重文件通过生成器生成图像。 但是如何使用权重生成图像呢? 一、参数配置 ima_size 为图像尺寸,这个需要跟你模型训练的时候resize的时候一样。 latent_dim为噪声维度,一般的设置都是…...

实时时钟(RTC)/日历芯片PCF8563的I2C读写驱动(2):功能介绍

0 参考资料 PCF8563数据手册&#xff08;第 11 版——2015 年 10 月 26 日&#xff09;.pdf 1 功能介绍 1.1 实时时钟&#xff08;RTC&#xff09;/日历 &#xff08;1&#xff09;PCF8563支持实时时钟&#xff08;RTC&#xff09;&#xff0c;提供时、分、秒信息。对应寄存器…...

python打卡day49

知识点回顾&#xff1a; 通道注意力模块复习空间注意力模块CBAM的定义 作业&#xff1a;尝试对今天的模型检查参数数目&#xff0c;并用tensorboard查看训练过程 import torch import torch.nn as nn# 定义通道注意力 class ChannelAttention(nn.Module):def __init__(self,…...

【JavaEE】-- HTTP

1. HTTP是什么&#xff1f; HTTP&#xff08;全称为"超文本传输协议"&#xff09;是一种应用非常广泛的应用层协议&#xff0c;HTTP是基于TCP协议的一种应用层协议。 应用层协议&#xff1a;是计算机网络协议栈中最高层的协议&#xff0c;它定义了运行在不同主机上…...

python/java环境配置

环境变量放一起 python&#xff1a; 1.首先下载Python Python下载地址&#xff1a;Download Python | Python.org downloads ---windows -- 64 2.安装Python 下面两个&#xff0c;然后自定义&#xff0c;全选 可以把前4个选上 3.环境配置 1&#xff09;搜高级系统设置 2…...

理解 MCP 工作流:使用 Ollama 和 LangChain 构建本地 MCP 客户端

&#x1f31f; 什么是 MCP&#xff1f; 模型控制协议 (MCP) 是一种创新的协议&#xff0c;旨在无缝连接 AI 模型与应用程序。 MCP 是一个开源协议&#xff0c;它标准化了我们的 LLM 应用程序连接所需工具和数据源并与之协作的方式。 可以把它想象成你的 AI 模型 和想要使用它…...

全球首个30米分辨率湿地数据集(2000—2022)

数据简介 今天我们分享的数据是全球30米分辨率湿地数据集&#xff0c;包含8种湿地亚类&#xff0c;该数据以0.5X0.5的瓦片存储&#xff0c;我们整理了所有属于中国的瓦片名称与其对应省份&#xff0c;方便大家研究使用。 该数据集作为全球首个30米分辨率、覆盖2000–2022年时间…...

从零实现STL哈希容器:unordered_map/unordered_set封装详解

本篇文章是对C学习的STL哈希容器自主实现部分的学习分享 希望也能为你带来些帮助~ 那咱们废话不多说&#xff0c;直接开始吧&#xff01; 一、源码结构分析 1. SGISTL30实现剖析 // hash_set核心结构 template <class Value, class HashFcn, ...> class hash_set {ty…...

大模型多显卡多服务器并行计算方法与实践指南

一、分布式训练概述 大规模语言模型的训练通常需要分布式计算技术,以解决单机资源不足的问题。分布式训练主要分为两种模式: 数据并行:将数据分片到不同设备,每个设备拥有完整的模型副本 模型并行:将模型分割到不同设备,每个设备处理部分模型计算 现代大模型训练通常结合…...

Device Mapper 机制

Device Mapper 机制详解 Device Mapper&#xff08;简称 DM&#xff09;是 Linux 内核中的一套通用块设备映射框架&#xff0c;为 LVM、加密磁盘、RAID 等提供底层支持。本文将详细介绍 Device Mapper 的原理、实现、内核配置、常用工具、操作测试流程&#xff0c;并配以详细的…...

Springboot社区养老保险系统小程序

一、前言 随着我国经济迅速发展&#xff0c;人们对手机的需求越来越大&#xff0c;各种手机软件也都在被广泛应用&#xff0c;但是对于手机进行数据信息管理&#xff0c;对于手机的各种软件也是备受用户的喜爱&#xff0c;社区养老保险系统小程序被用户普遍使用&#xff0c;为方…...

20个超级好用的 CSS 动画库

分享 20 个最佳 CSS 动画库。 它们中的大多数将生成纯 CSS 代码&#xff0c;而不需要任何外部库。 1.Animate.css 一个开箱即用型的跨浏览器动画库&#xff0c;可供你在项目中使用。 2.Magic Animations CSS3 一组简单的动画&#xff0c;可以包含在你的网页或应用项目中。 3.An…...