pai_flow_operator2.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import re
  4. import sys
  5. from sre_constants import error
  6. from typing import List
  7. import time
  8. import json
  9. import pandas as pd
  10. from alibabacloud_paistudio20210202.client import Client as PaiStudio20210202Client
  11. from alibabacloud_tea_openapi import models as open_api_models
  12. from alibabacloud_paistudio20210202 import models as pai_studio_20210202_models
  13. from alibabacloud_tea_util import models as util_models
  14. from alibabacloud_tea_util.client import Client as UtilClient
  15. from alibabacloud_eas20210701.client import Client as eas20210701Client
  16. from alibabacloud_paiflow20210202 import models as paiflow_20210202_models
  17. from alibabacloud_paiflow20210202.client import Client as PAIFlow20210202Client
  18. from datetime import datetime, timedelta
  19. from odps import ODPS
  20. from ad_monitor_util import _monitor
  21. target_names = {
  22. '样本shuffle',
  23. '模型训练-样本shufle',
  24. '模型训练-自定义',
  25. '模型增量训练',
  26. '模型导出-2',
  27. '更新EAS服务(Beta)-1',
  28. '虚拟起始节点',
  29. '二分类评估-1',
  30. '二分类评估-2',
  31. '预测结果对比'
  32. }
  33. experiment_id = "draft-kbezr8f0q3cpee9eqc"
  34. def get_odps_instance(project):
  35. odps = ODPS(
  36. access_id='LTAIWYUujJAm7CbH',
  37. secret_access_key='RfSjdiWwED1sGFlsjXv0DlfTnZTG1P',
  38. project=project,
  39. endpoint='http://service.cn.maxcompute.aliyun.com/api',
  40. )
  41. return odps
  42. def get_data_from_odps(project, table, num):
  43. odps = get_odps_instance(project)
  44. try:
  45. # 要查询的 SQL 语句
  46. sql = f'select * from {table} limit {num}'
  47. # 执行 SQL 查询
  48. with odps.execute_sql(sql).open_reader() as reader:
  49. # 查询数量小于目标数量时 返回空
  50. if reader.count < num:
  51. return None
  52. # 获取字段名称
  53. column_names = reader.schema.names
  54. # 获取查询结果数据
  55. data = []
  56. for record in reader:
  57. record_list = list(record)
  58. numbers = []
  59. for item in record_list:
  60. numbers.append(item[1])
  61. data.append(numbers)
  62. # 将数据和字段名称组合成 DataFrame
  63. df = pd.DataFrame(data, columns=column_names)
  64. return df
  65. except Exception as e:
  66. print(f"发生错误: {e}")
  67. def get_dict_from_odps(project, table):
  68. odps = get_odps_instance(project)
  69. try:
  70. # 要查询的 SQL 语句
  71. sql = f'select * from {table}'
  72. # 执行 SQL 查询
  73. with odps.execute_sql(sql).open_reader() as reader:
  74. data = {}
  75. for record in reader:
  76. record_list = list(record)
  77. key = record_list[0][1]
  78. value = record_list[1][1]
  79. data[key] = value
  80. return data
  81. except Exception as e:
  82. print(f"发生错误: {e}")
  83. def get_dates_between(start_date_str, end_date_str):
  84. start_date = datetime.strptime(start_date_str, '%Y%m%d')
  85. end_date = datetime.strptime(end_date_str, '%Y%m%d')
  86. dates = []
  87. current_date = start_date
  88. while current_date <= end_date:
  89. dates.append(current_date.strftime('%Y%m%d'))
  90. current_date += timedelta(days=1)
  91. return dates
  92. def read_file_to_list():
  93. try:
  94. current_dir = os.getcwd()
  95. file_path = os.path.join(current_dir, 'holidays.txt')
  96. with open(file_path, 'r', encoding='utf-8') as file:
  97. content = file.read()
  98. return content.split('\n')
  99. except FileNotFoundError:
  100. print(f"错误:未找到 {file_path} 文件。")
  101. except Exception as e:
  102. print(f"错误:发生了一个未知错误: {e}")
  103. return []
  104. def get_previous_days_date(days):
  105. current_date = datetime.now()
  106. previous_date = current_date - timedelta(days=days)
  107. return previous_date.strftime('%Y%m%d')
  108. def remove_elements(lst1, lst2):
  109. return [element for element in lst1 if element not in lst2]
  110. def process_list(lst, append_str):
  111. # 给列表中每个元素拼接相同的字符串
  112. appended_list = [append_str + element for element in lst]
  113. # 将拼接后的列表元素用逗号拼接成一个字符串
  114. result_str = ','.join(appended_list)
  115. return result_str
  116. def get_train_data_list():
  117. start_date = '20250223'
  118. end_date = get_previous_days_date(2)
  119. date_list = get_dates_between(start_date, end_date)
  120. filter_date_list = read_file_to_list()
  121. date_list = remove_elements(date_list, filter_date_list)
  122. return date_list
  123. def update_train_tables(old_str):
  124. date_list = get_train_data_list()
  125. train_list = ["'" + item + "'" for item in date_list]
  126. result = ','.join(train_list)
  127. start_index = old_str.find('where dt in (')
  128. if start_index != -1:
  129. equal_sign_index = start_index + len('where dt in (')
  130. # 找到下一个双引号的位置
  131. next_quote_index = old_str.find(')', equal_sign_index)
  132. if next_quote_index != -1:
  133. # 进行替换
  134. new_value = old_str[:equal_sign_index] + result + old_str[next_quote_index:]
  135. return new_value
  136. return None
  137. def update_train_table(old_str, table):
  138. address = 'odps://pai_algo/tables/'
  139. train_table = address + table
  140. start_index = old_str.find('-Dtrain_tables="')
  141. if start_index != -1:
  142. # 确定等号的位置
  143. equal_sign_index = start_index + len('-Dtrain_tables="')
  144. # 找到下一个双引号的位置
  145. next_quote_index = old_str.find('"', equal_sign_index)
  146. if next_quote_index != -1:
  147. # 进行替换
  148. new_value = old_str[:equal_sign_index] + train_table + old_str[next_quote_index:]
  149. return new_value
  150. return None
  151. class PAIClient:
  152. def __init__(self):
  153. pass
  154. @staticmethod
  155. def create_client() -> PaiStudio20210202Client:
  156. """
  157. 使用AK&SK初始化账号Client
  158. @return: Client
  159. @throws Exception
  160. """
  161. # 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
  162. # 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
  163. config = open_api_models.Config(
  164. access_key_id="LTAI5tFGqgC8f3mh1fRCrAEy",
  165. access_key_secret="XhOjK9XmTYRhVAtf6yii4s4kZwWzvV"
  166. )
  167. # Endpoint 请参考 https://api.aliyun.com/product/PaiStudio
  168. config.endpoint = f'pai.cn-hangzhou.aliyuncs.com'
  169. return PaiStudio20210202Client(config)
  170. @staticmethod
  171. def create_eas_client() -> eas20210701Client:
  172. """
  173. 使用AK&SK初始化账号Client
  174. @return: Client
  175. @throws Exception
  176. """
  177. # 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
  178. # 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
  179. config = open_api_models.Config(
  180. access_key_id="LTAI5tFGqgC8f3mh1fRCrAEy",
  181. access_key_secret="XhOjK9XmTYRhVAtf6yii4s4kZwWzvV"
  182. )
  183. # Endpoint 请参考 https://api.aliyun.com/product/PaiStudio
  184. config.endpoint = f'pai-eas.cn-hangzhou.aliyuncs.com'
  185. return eas20210701Client(config)
  186. @staticmethod
  187. def create_flow_client() -> PAIFlow20210202Client:
  188. """
  189. 使用AK&SK初始化账号Client
  190. @return: Client
  191. @throws Exception
  192. """
  193. # 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
  194. # 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
  195. config = open_api_models.Config(
  196. # 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
  197. access_key_id="LTAI5tFGqgC8f3mh1fRCrAEy",
  198. # 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
  199. access_key_secret="XhOjK9XmTYRhVAtf6yii4s4kZwWzvV"
  200. )
  201. # Endpoint 请参考 https://api.aliyun.com/product/PAIFlow
  202. config.endpoint = f'paiflow.cn-hangzhou.aliyuncs.com'
  203. return PAIFlow20210202Client(config)
  204. @staticmethod
  205. def get_work_flow_draft_list(workspace_id: str):
  206. client = PAIClient.create_client()
  207. list_experiments_request = pai_studio_20210202_models.ListExperimentsRequest(
  208. workspace_id=workspace_id
  209. )
  210. runtime = util_models.RuntimeOptions()
  211. headers = {}
  212. try:
  213. resp = client.list_experiments_with_options(list_experiments_request, headers, runtime)
  214. return resp.body.to_map()
  215. except Exception as error:
  216. print(error.message)
  217. print(error.data.get("Recommend"))
  218. UtilClient.assert_as_string(error.message)
  219. @staticmethod
  220. def get_work_flow_draft(experiment_id: str):
  221. client = PAIClient.create_client()
  222. runtime = util_models.RuntimeOptions()
  223. headers = {}
  224. try:
  225. # 复制代码运行请自行打印 API 的返回值
  226. resp = client.get_experiment_with_options(experiment_id, headers, runtime)
  227. return resp.body.to_map()
  228. except Exception as error:
  229. # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
  230. # 错误 message
  231. print(error.message)
  232. # 诊断地址
  233. print(error.data.get("Recommend"))
  234. UtilClient.assert_as_string(error.message)
  235. @staticmethod
  236. def get_describe_service(service_name: str):
  237. client = PAIClient.create_eas_client()
  238. runtime = util_models.RuntimeOptions()
  239. headers = {}
  240. try:
  241. # 复制代码运行请自行打印 API 的返回值
  242. resp = client.describe_service_with_options('cn-hangzhou', service_name, headers, runtime)
  243. return resp.body.to_map()
  244. except Exception as error:
  245. # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
  246. # 错误 message
  247. print(error.message)
  248. # 诊断地址
  249. print(error.data.get("Recommend"))
  250. UtilClient.assert_as_string(error.message)
  251. @staticmethod
  252. def update_experiment_content(experiment_id: str, content: str, version: int):
  253. client = PAIClient.create_client()
  254. update_experiment_content_request = pai_studio_20210202_models.UpdateExperimentContentRequest(content=content,
  255. version=version)
  256. runtime = util_models.RuntimeOptions()
  257. headers = {}
  258. try:
  259. # 复制代码运行请自行打印 API 的返回值
  260. resp = client.update_experiment_content_with_options(experiment_id, update_experiment_content_request,
  261. headers, runtime)
  262. print(resp.body.to_map())
  263. except Exception as error:
  264. # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
  265. # 错误 message
  266. print(error.message)
  267. # 诊断地址
  268. print(error.data.get("Recommend"))
  269. UtilClient.assert_as_string(error.message)
  270. @staticmethod
  271. def create_job(experiment_id: str, node_id: str, execute_type: str):
  272. client = PAIClient.create_client()
  273. create_job_request = pai_studio_20210202_models.CreateJobRequest()
  274. create_job_request.experiment_id = experiment_id
  275. create_job_request.node_id = node_id
  276. create_job_request.execute_type = execute_type
  277. runtime = util_models.RuntimeOptions()
  278. headers = {}
  279. try:
  280. # 复制代码运行请自行打印 API 的返回值
  281. resp = client.create_job_with_options(create_job_request, headers, runtime)
  282. return resp.body.to_map()
  283. except Exception as error:
  284. # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
  285. # 错误 message
  286. print(error.message)
  287. # 诊断地址
  288. print(error.data.get("Recommend"))
  289. UtilClient.assert_as_string(error.message)
  290. @staticmethod
  291. def get_job_detail(job_id: str):
  292. client = PAIClient.create_client()
  293. get_job_request = pai_studio_20210202_models.GetJobRequest(
  294. verbose=False
  295. )
  296. runtime = util_models.RuntimeOptions()
  297. headers = {}
  298. try:
  299. # 复制代码运行请自行打印 API 的返回值
  300. resp = client.get_job_with_options(job_id, get_job_request, headers, runtime)
  301. return resp.body.to_map()
  302. except Exception as error:
  303. # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
  304. # 错误 message
  305. print(error.message)
  306. # 诊断地址
  307. print(error.data.get("Recommend"))
  308. UtilClient.assert_as_string(error.message)
  309. @staticmethod
  310. def get_flow_out_put(pipeline_run_id: str, node_id: str, depth: int):
  311. client = PAIClient.create_flow_client()
  312. list_pipeline_run_node_outputs_request = paiflow_20210202_models.ListPipelineRunNodeOutputsRequest(
  313. depth=depth
  314. )
  315. runtime = util_models.RuntimeOptions()
  316. headers = {}
  317. try:
  318. # 复制代码运行请自行打印 API 的返回值
  319. resp = client.list_pipeline_run_node_outputs_with_options(pipeline_run_id, node_id,
  320. list_pipeline_run_node_outputs_request, headers,
  321. runtime)
  322. return resp.body.to_map()
  323. except Exception as error:
  324. # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
  325. # 错误 message
  326. print(error.message)
  327. # 诊断地址
  328. print(error.data.get("Recommend"))
  329. UtilClient.assert_as_string(error.message)
  330. def extract_date_yyyymmdd(input_string):
  331. pattern = r'\d{8}'
  332. matches = re.findall(pattern, input_string)
  333. if matches:
  334. return matches[0]
  335. return None
  336. def get_online_version_dt(service_name: str):
  337. model_detail = PAIClient.get_describe_service(service_name)
  338. service_config_str = model_detail['ServiceConfig']
  339. service_config = json.loads(service_config_str)
  340. model_path = service_config['model_path']
  341. online_date = extract_date_yyyymmdd(model_path)
  342. return online_date
  343. def update_online_flow():
  344. online_version_dt = get_online_version_dt('ad_rank_dnn_v11_easyrec')
  345. draft = PAIClient.get_work_flow_draft(experiment_id)
  346. print(json.dumps(draft, ensure_ascii=False))
  347. content = draft['Content']
  348. version = draft['Version']
  349. print(content)
  350. content_json = json.loads(content)
  351. nodes = content_json.get('nodes')
  352. global_params = content_json.get('globalParams')
  353. bizdate = get_previous_days_date(1)
  354. for global_param in global_params:
  355. if global_param['name'] == 'bizdate':
  356. global_param['value'] = bizdate
  357. if global_param['name'] == 'online_version_dt':
  358. global_param['value'] = online_version_dt
  359. if global_param['name'] == 'eval_date':
  360. global_param['value'] = bizdate
  361. for node in nodes:
  362. name = node['name']
  363. if name == '样本shuffle':
  364. properties = node['properties']
  365. for property in properties:
  366. if property['name'] == 'sql':
  367. value = property['value']
  368. new_value = update_train_tables(value)
  369. if new_value is None:
  370. print("error")
  371. property['value'] = new_value
  372. new_content = json.dumps(content_json, ensure_ascii=False)
  373. PAIClient.update_experiment_content(experiment_id, new_content, version)
  374. def update_shuffle_flow(table):
  375. draft = PAIClient.get_work_flow_draft(experiment_id)
  376. print(json.dumps(draft, ensure_ascii=False))
  377. content = draft['Content']
  378. version = draft['Version']
  379. content_json = json.loads(content)
  380. nodes = content_json.get('nodes')
  381. for node in nodes:
  382. name = node['name']
  383. if name == '模型训练-样本shufle':
  384. properties = node['properties']
  385. for property in properties:
  386. if property['name'] == 'sql':
  387. value = property['value']
  388. new_value = update_train_table(value, table)
  389. if new_value is None:
  390. print("error")
  391. property['value'] = new_value
  392. new_content = json.dumps(content_json, ensure_ascii=False)
  393. PAIClient.update_experiment_content(experiment_id, new_content, version)
  394. def update_shuffle_flow_1():
  395. draft = PAIClient.get_work_flow_draft(experiment_id)
  396. print(json.dumps(draft, ensure_ascii=False))
  397. content = draft['Content']
  398. version = draft['Version']
  399. print(content)
  400. content_json = json.loads(content)
  401. nodes = content_json.get('nodes')
  402. for node in nodes:
  403. name = node['name']
  404. if name == '模型训练-样本shufle':
  405. properties = node['properties']
  406. for property in properties:
  407. if property['name'] == 'sql':
  408. value = property['value']
  409. new_value = update_train_tables(value)
  410. if new_value is None:
  411. print("error")
  412. property['value'] = new_value
  413. new_content = json.dumps(content_json, ensure_ascii=False)
  414. PAIClient.update_experiment_content(experiment_id, new_content, version)
  415. def wait_job_end(job_id: str):
  416. while True:
  417. job_detail = PAIClient.get_job_detail(job_id)
  418. print(job_detail)
  419. statue = job_detail['Status']
  420. # Initialized: 初始化完成 Starting:开始 WorkflowServiceStarting:准备提交 Running:运行中 ReadyToSchedule:准备运行(前序节点未完成导致)
  421. if (statue == 'Initialized' or statue == 'Starting' or statue == 'WorkflowServiceStarting'
  422. or statue == 'Running' or statue == 'ReadyToSchedule'):
  423. # 睡眠300s 等待下次获取
  424. time.sleep(300)
  425. continue
  426. # Failed:运行失败 Terminating:终止中 Terminated:已终止 Unknown:未知 Skipped:跳过(前序节点失败导致) Succeeded:运行成功
  427. if statue == 'Failed' or statue == 'Terminating' or statue == 'Unknown' or statue == 'Skipped' or statue == 'Succeeded':
  428. return job_detail
  429. def get_node_dict():
  430. draft = PAIClient.get_work_flow_draft(experiment_id)
  431. content = draft['Content']
  432. content_json = json.loads(content)
  433. nodes = content_json.get('nodes')
  434. node_dict = {}
  435. for node in nodes:
  436. name = node['name']
  437. # 检查名称是否在目标名称集合中
  438. if name in target_names:
  439. node_dict[name] = node['id']
  440. return node_dict
  441. def train_model():
  442. node_dict = get_node_dict()
  443. train_node_id = node_dict['样本shuffle']
  444. execute_type = 'EXECUTE_ONE'
  445. validate_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  446. validate_job_id = validate_res['JobId']
  447. validate_job_detail = wait_job_end(validate_job_id)
  448. if validate_job_detail['Status'] == 'Succeeded':
  449. pipeline_run_id = validate_job_detail['RunId']
  450. node_id = validate_job_detail['PaiflowNodeId']
  451. flow_out_put_detail = PAIClient.get_flow_out_put(pipeline_run_id, node_id, 2)
  452. out_puts = flow_out_put_detail['Outputs']
  453. table = None
  454. for out_put in out_puts:
  455. if out_put["Producer"] == node_dict['样本shuffle'] and out_put["Name"] == "outputTable":
  456. value1 = json.loads(out_put["Info"]['value'])
  457. table = value1['location']['table']
  458. if table is not None:
  459. update_shuffle_flow(table)
  460. node_dict = get_node_dict()
  461. train_node_id = node_dict['模型训练-样本shufle']
  462. execute_type = 'EXECUTE_ONE'
  463. train_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  464. train_job_id = train_res['JobId']
  465. train_job_detail = wait_job_end(train_job_id)
  466. if train_job_detail['Status'] == 'Succeeded':
  467. export_node_id = node_dict['模型导出-2']
  468. export_res = PAIClient.create_job(experiment_id, export_node_id, execute_type)
  469. export_job_id = export_res['JobId']
  470. export_job_detail = wait_job_end(export_job_id)
  471. if export_job_detail['Status'] == 'Succeeded':
  472. return True
  473. return False
  474. def update_online_model():
  475. node_dict = get_node_dict()
  476. train_node_id = node_dict['更新EAS服务(Beta)-1']
  477. execute_type = 'EXECUTE_ONE'
  478. train_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  479. train_job_id = train_res['JobId']
  480. train_job_detail = wait_job_end(train_job_id)
  481. if train_job_detail['Status'] == 'Succeeded':
  482. return True
  483. return False
  484. def validate_model_data_accuracy(start_time):
  485. node_dict = get_node_dict()
  486. train_node_id = node_dict['虚拟起始节点']
  487. execute_type = 'EXECUTE_FROM_HERE'
  488. validate_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  489. validate_job_id = validate_res['JobId']
  490. validate_job_detail = wait_job_end(validate_job_id)
  491. if validate_job_detail['Status'] == 'Succeeded':
  492. pipeline_run_id = validate_job_detail['RunId']
  493. node_id = validate_job_detail['PaiflowNodeId']
  494. flow_out_put_detail = PAIClient.get_flow_out_put(pipeline_run_id, node_id, 3)
  495. print(flow_out_put_detail)
  496. tabel_dict = {}
  497. out_puts = flow_out_put_detail['Outputs']
  498. for out_put in out_puts:
  499. if out_put["Producer"] == node_dict['二分类评估-1'] and out_put["Name"] == "outputMetricTable":
  500. value1 = json.loads(out_put["Info"]['value'])
  501. tabel_dict['二分类评估-1'] = value1['location']['table']
  502. if out_put["Producer"] == node_dict['二分类评估-2'] and out_put["Name"] == "outputMetricTable":
  503. value2 = json.loads(out_put["Info"]['value'])
  504. tabel_dict['二分类评估-2'] = value2['location']['table']
  505. if out_put["Producer"] == node_dict['预测结果对比'] and out_put["Name"] == "outputTable":
  506. value3 = json.loads(out_put["Info"]['value'])
  507. tabel_dict['预测结果对比'] = value3['location']['table']
  508. num = 10
  509. df = get_data_from_odps('pai_algo', tabel_dict['预测结果对比'], 10)
  510. # 对指定列取绝对值再求和
  511. old_abs_avg = df['old_error'].abs().sum() / num
  512. new_abs_avg = df['new_error'].abs().sum() / num
  513. new_auc = get_dict_from_odps('pai_algo', tabel_dict['二分类评估-1'])['AUC']
  514. old_auc = get_dict_from_odps('pai_algo', tabel_dict['二分类评估-2'])['AUC']
  515. bizdate = get_previous_days_date(1)
  516. score_diff = abs(old_abs_avg - new_abs_avg)
  517. msg = ""
  518. level = ""
  519. if new_abs_avg > 0.1:
  520. msg += f'线上模型评估{bizdate}的数据,绝对误差大于0.1,请检查'
  521. level = 'error'
  522. elif score_diff > 0.05:
  523. msg += f'两个模型评估${bizdate}的数据,两个模型分数差异为: ${score_diff}, 大于0.05, 请检查'
  524. level = 'error'
  525. else:
  526. # update_online_model()
  527. msg += 'DNN广告模型更新完成'
  528. level = 'info'
  529. step_end_time = int(time.time())
  530. elapsed = step_end_time - start_time
  531. # 初始化表格头部
  532. top10_msg = "| CID | 老模型相对真实CTCVR的变化 | 新模型相对真实CTCVR的变化 |"
  533. top10_msg += "\n| ---- | --------- | -------- |"
  534. for index, row in df.iterrows():
  535. # 获取指定列的元素
  536. cid = row['cid']
  537. old_error = row['old_error']
  538. new_error = row['new_error']
  539. top10_msg += f"\n| {int(cid)} | {old_error} | {new_error} | "
  540. print(top10_msg)
  541. msg += f"\n\t - 老模型AUC: {old_auc}"
  542. msg += f"\n\t - 新模型AUC: {new_auc}"
  543. msg += f"\n\t - 老模型Top10差异平均值: {old_abs_avg}"
  544. msg += f"\n\t - 新模型Top10差异平均值: {new_abs_avg}"
  545. _monitor(level, msg, start_time, elapsed, top10_msg)
  546. if __name__ == '__main__':
  547. start_time = int(time.time())
  548. # 1.更新工作流
  549. update_online_flow()
  550. # 2.训练模型
  551. train_res = train_model()
  552. if train_res:
  553. # 3. 验证模型数据 & 更新模型到线上
  554. validate_model_data_accuracy(start_time)
  555. else:
  556. print('train_model_error')