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.pswp.cn/diannao/70885.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/70885.shtml
英文地址,請注明出處:http://en.pswp.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;…