pai_flow_operator2.py 24 KB

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