File size: 35,087 Bytes
cb5f642 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 | {
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install xgboost"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 这是一段典型的“多模态特征 + 二分类”实验脚本,核心目的:\n",
"\n",
"# 用 XGBoost 等模型对样本进行二分类;\n",
"# 计算并绘制 Precision-Recall 曲线,找出在 precision≈0.8 时的阈值与召回率;\n",
"# 分别评估单特征与融合特征的贡献。\n",
"\n",
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import sklearn\n",
"from sklearn.ensemble import BaggingClassifier\n",
"from sklearn.tree import DecisionTreeClassifier\n",
"from sklearn.preprocessing import StandardScaler\n",
"import csv\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.metrics import accuracy_score\n",
"from sklearn.metrics import confusion_matrix\n",
"from sklearn.metrics import classification_report\n",
"from sklearn.ensemble import GradientBoostingClassifier\n",
"from sklearn.linear_model import LogisticRegression\n",
"from xgboost import XGBClassifier\n",
"\n",
"def precision_recall(y_true, y_score, test_material_cnt=0):\n",
" precision, recall = [], []\n",
" for idx, threshold in enumerate(np.linspace(0, 1, num=100)):\n",
" y_pred = np.where(y_score >= threshold, 1, 0)\n",
" tp, fp, fn = test_material_cnt, 0, 0\n",
" for i in range(len(y_true)):\n",
" if y_pred[i] == 1 and y_true[i] == 1:\n",
" tp += 1\n",
" elif y_pred[i] == 1 and y_true[i] == 0:\n",
" fp += 1\n",
" elif y_pred[i] == 0 and y_true[i] == 1:\n",
" fn += 1\n",
" if (tp + fp) == 0:\n",
" precision.append(0)\n",
" else:\n",
" precision.append(tp / (tp + fp))\n",
" if (tp + fn) == 0:\n",
" recall.append(0)\n",
" else:\n",
" recall.append(tp / (tp + fn))\n",
" # 过滤掉 precision=0 的元素及其对应的 recall\n",
" filtered_pairs = [(p, r) for p, r in zip(precision, recall) if p != 0]\n",
"\n",
" # 拆分回两个列表\n",
" precision_filtered, recall_filtered = zip(*filtered_pairs) # 返回元组,如需列表可转换\n",
" auc = np.trapz(precision[::-1], recall[::-1])\n",
" return precision, recall, auc\n",
"\n",
"def calculate_classification_report(confusion_matrix):\n",
" TP = confusion_matrix[1, 1] # True Positive\n",
" TN = confusion_matrix[0, 0] # True Negative\n",
" FP = confusion_matrix[0, 1] # False Positive\n",
" FN = confusion_matrix[1, 0] # False Negative\n",
"\n",
" precision_0 = TN / (TN + FN) if (TN + FN) != 0 else 0\n",
" recall_0 = TN / (TN + FP) if (TN + FP) != 0 else 0\n",
" f1_0 = 2 * precision_0 * recall_0 / (precision_0 + recall_0) if (precision_0 + recall_0) != 0 else 0\n",
"\n",
" precision_1 = TP / (TP + FP) if (TP + FP) != 0 else 0\n",
" recall_1 = TP / (TP + FN) if (TP + FN) != 0 else 0\n",
" f1_1 = 2 * precision_1 * recall_1 / (precision_1 + recall_1) if (precision_1 + recall_1) != 0 else 0\n",
"\n",
" precision_macro = (precision_0 + precision_1) / 2\n",
" recall_macro = (recall_0 + recall_1) / 2\n",
" f1_macro = (f1_0 + f1_1) / 2\n",
"\n",
" support_0 = TN + FP\n",
" support_1 = TP + FN\n",
" total_support = support_0 + support_1\n",
"\n",
" precision_weighted = (precision_0 * support_0 + precision_1 * support_1) / total_support\n",
" recall_weighted = (recall_0 * support_0 + recall_1 * support_1) / total_support\n",
" f1_weighted = (f1_0 * support_0 + f1_1 * support_1) / total_support\n",
"\n",
" print(f\"{'':<12}{'Precision':<12}{'Recall':<12}{'F1-Score':<12}{'Support':<12}\")\n",
" print(f\"{'Class 1':<12}{precision_1:.2f}{'':<4}{recall_1:.2f}{'':<4}{f1_1:.2f}{'':<4}{support_1:<12}\")\n",
"\n",
"\n",
"import matplotlib.pyplot as plt\n",
"\n",
"def calc_precision_test(feats, labels, xgb_model):\n",
" feats = [ele[0:7] + ele[8:12] for ele in feats]\n",
" preds = xgb_model.predict_proba(feats)\n",
" preds = [1 if pred >= 0.3838 else 0 for pred in preds[:, 1]]\n",
" matches = sum(1 for p, m in zip(preds, labels) if p == m)\n",
" total = len(preds)\n",
" match_ratio = matches / total\n",
"\n",
" return matches, total, match_ratio\n",
"\n",
"# mn, tt, mr = calc_precision_test(man_lb1_feats, man_lb1, clf_xgb_4tier_fe)\n",
"# print(\"细粒度主题相似,相同数量:{},总数量:{}, 准确率:{}\".format(mn, tt, round(mr, 6)))\n",
"\n",
"# mn, tt, mr = calc_precision_test(man_lb4_feats, man_lb4, clf_xgb_4tier_fe)\n",
"# print(\"大众主题相似,相同数量:{},总数量:{}, 准确率:{}\".format(mn, tt, round(mr, 6)))\n",
"\n",
"def calc_pr_test(feats, labels, xgb_model, flag=''):\n",
" # feats = [ele[0:8] + ele[8:12] for ele in feats]\n",
" # print(feats)\n",
" predict_scores = xgb_model.predict_proba(feats)\n",
" precision, recall, auc = precision_recall(labels, predict_scores[:, 1])\n",
" for i in range(len(precision)):\n",
" if abs(precision[i] - 0.8) < 0.01:\n",
" print(\"{} xgboost thres: \".format(flag), np.linspace(0, 1, num=100)[i], \"recall: \", recall[i], \"precision: \", precision[i])\n",
" return precision, recall, auc\n",
"\n",
"def plot_ue_pr(features_test, labels_test, xgb, feat_names=['mm', 'visual', 'text', 'mmcf', 'ocr', 'asr', 'rq'], colors=['navy', 'darkorange', 'darkgreen', 'purple', 'magenta', 'cyan', 'lime', 'gold'], flag=''):\n",
" idx = 0\n",
" plt.figure(figsize=(16, 12))\n",
" for feat_name in feat_names:\n",
" score = [float(feature[idx]) for feature in features_test]\n",
" print('feat_name:{}'.format(feat_name))\n",
" print(score[0:100])\n",
" precision, recall, auc = precision_recall(labels_test, score)\n",
" for i in range(len(precision)):\n",
" if abs(precision[i] - 0.8) < 0.01:\n",
" print(\"{} {} thres: \".format(flag, feat_name), np.linspace(0, 1, num=100)[i], \"recall: \", recall[i], \"precision: \", precision[i])\n",
" \n",
" plt.plot(recall, precision, lw=2, color=colors[idx], label='{} PR curve AUC = {}'.format(feat_name, auc))\n",
" idx += 1\n",
"\n",
" precision_xgb, recall_xgb, auc_xgb = calc_pr_test(features_test, labels_test, xgb, flag)\n",
" \n",
" plt.plot(recall_xgb, precision_xgb, lw=2, color='gold', label='xgboost PR curve (AUC = %0.2f)' % auc_xgb)\n",
" plt.xlabel('Recall')\n",
" plt.ylabel('Precision')\n",
" plt.xlim([0.0, 1.0])\n",
" plt.ylim([0.0, 1.05])\n",
" plt.title('{} Precision-Recall curve'.format(flag))\n",
" plt.legend(loc='best')\n",
" plt.show()\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 获取数据\n",
"\n",
"!hdfs dfs -get hdfs://harunasg/home/byte_data_rec_content_sg_training/tiktok_proactive_publish_instance/wy_test/train_dataset/rwc_data/train_features_ar_jp_merge_202507_202510_add_interest_neg_ratio_20_add_interest.json\n",
"!hdfs dfs -get hdfs://harunasg/home/byte_data_rec_content_sg_training/tiktok_proactive_publish_instance/wy_test/train_dataset/rwc_data/train_labels_ar_jp_merge_202507_202510_add_interest_neg_ratio_20_add_interest.json\n",
"!hdfs dfs -get hdfs://harunasg/home/byte_data_rec_content_sg_training/tiktok_proactive_publish_instance/wy_test/train_dataset/rwc_data/test_features_20251119_eu_filter_interest4.json\n",
"!hdfs dfs -get hdfs://harunasg/home/byte_data_rec_content_sg_training/tiktok_proactive_publish_instance/wy_test/train_dataset/rwc_data/test_labels_20251119_eu_filter_interest4.json\n",
"\n",
"import json\n",
"\n",
"with open('train_features_ar_jp_merge_202507_202510_add_interest_neg_ratio_20_add_interest.json', 'r') as f:\n",
" features_train_q3_afev1 = json.load(f)\n",
"\n",
"with open('train_labels_ar_jp_merge_202507_202510_add_interest_neg_ratio_20_add_interest.json', 'r') as f:\n",
" labels_train_q3_afev1 = json.load(f)\n",
"\n",
"\n",
"# 读取时使用\n",
"with open('test_features_20251119_eu_filter_interest4.json', 'r') as f:\n",
" features_test_q3_afev1 = json.load(f)\n",
"\n",
"with open('test_labels_20251119_eu_filter_interest4.json', 'r') as f:\n",
" labels_test_q3_afev1 = json.load(f)\n",
"\n",
"\n",
"flag = '4tier_feat'\n",
"feats_tr_lst = []\n",
"feats_te_lst = []\n",
"features_train = features_train_q3_afev1\n",
"labels_train = labels_train_q3_afev1\n",
"features_test = features_test_q3_afev1\n",
"labels_test = labels_test_q3_afev1\n",
"for ele in features_train:\n",
" feat = ele\n",
" feats_tr_lst.append(feat)\n",
"\n",
"for ele in features_test:\n",
" feat = ele\n",
" feats_te_lst.append(feat)\n",
"\n",
"clf_xgb_4tier_fe = XGBClassifier(n_estimators=20, learning_rate=0.1, max_depth=5)\n",
"clf_xgb_4tier_fe.fit(feats_tr_lst, labels_train) \n",
"predict_results=clf_xgb_4tier_fe.predict(feats_te_lst)\n",
"conf_mat = confusion_matrix(labels_test, predict_results)\n",
"\n",
"print(conf_mat)\n",
"calculate_classification_report(conf_mat)\n",
"\n",
"predict_scores = clf_xgb_4tier_fe.predict_proba(feats_te_lst)\n",
"precision_xgb_4tier_fe, recall_xgb_4tier_fe, auc_xgb_4tier_fe = precision_recall(labels_test, predict_scores[:, 1])\n",
"\n",
"print(auc_xgb_4tier_fe)\n",
"\n",
"for i in range(len(precision_xgb_4tier_fe)):\n",
" if abs(precision_xgb_4tier_fe[i] - 0.80) < 0.01:\n",
" print(\"xgb_4tier_fe thres: \", np.linspace(0, 1, num=100)[i], \"recall: \", recall_xgb_4tier_fe[i], \"precision: \", precision_xgb_4tier_fe[i])\n",
"\n",
"plot_ue_pr(feats_te_lst, labels_test, clf_xgb_4tier_fe, flag='Q3Q4ROW训练数据(正样本5w)')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(feats_te_lst[0])\n",
"print(len(feats_te_lst[0]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": "import joblib\nimport tempfile\nimport subprocess\nimport os\nimport shutil\n\n# 保存模型到本地临时文件\nwith tempfile.NamedTemporaryFile(suffix='.pkl', delete=False) as tmp_file:\n local_model_path = tmp_file.name\n joblib.dump(clf_xgb_4tier_fe, local_model_path)\n\n# 本地保存路径\nlocal_save_dir = \"/mnt/bn/bohanzhainas1/jiashuo/active_proaction/xgboost_attribution_model_v3\"\nlocal_model_save_path = os.path.join(local_save_dir, \"model.pkl\")\n\ntry:\n # 确保本地目录存在\n os.makedirs(local_save_dir, exist_ok=True)\n \n # 复制模型文件到本地目录\n shutil.copy(local_model_path, local_model_save_path)\n \n print(f\"模型已成功保存到: {local_model_save_path}\")\n \n # 可选:同时保存模型配置信息\n model_info = {\n 'n_estimators': 20,\n 'learning_rate': 0.1,\n 'max_depth': 5,\n 'feature_names': feature_names if 'feature_names' in locals() else None\n }\n \n info_path = local_model_path + '_info.pkl'\n joblib.dump(model_info, info_path)\n shutil.copy(info_path, os.path.join(local_save_dir, \"model_info.pkl\"))\n \nfinally:\n # 清理临时文件\n os.unlink(local_model_path)\n if os.path.exists(info_path):\n os.unlink(info_path)"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!hdfs dfs -ls hdfs://harunasg/home/byte_data_rec_content_sg_training/tiktok_proactive_publish_instance/wy_test/xgboost_attribution_model_v3/"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import joblib\n",
"import pandas as pd\n",
"import numpy as np\n",
"from xgboost import XGBClassifier\n",
"# import pydoop.hdfs as hdfs # 或者使用 hdfs 库\n",
"\n",
"# 方法2:先将文件下载到本地再加载\n",
"def load_model_with_download(hdfs_path, local_temp_path=\"/tmp/temp_model\"):\n",
" \"\"\"\n",
" 先将 HDFS 文件下载到本地,再加载模型\n",
" \"\"\"\n",
" import subprocess\n",
" import os\n",
" \n",
" # 创建临时目录\n",
" os.makedirs(local_temp_path, exist_ok=True)\n",
" \n",
" # 下载模型文件\n",
" model_hdfs = f\"{hdfs_path}/model.pkl\"\n",
" model_info_hdfs = f\"{hdfs_path}/model_info.pkl\"\n",
" model_local = f\"{local_temp_path}/model.pkl\"\n",
" model_info_local = f\"{local_temp_path}/model_info.pkl\"\n",
" \n",
" # 使用 hdfs dfs -get 命令下载\n",
" subprocess.run([\"hdfs\", \"dfs\", \"-get\", model_hdfs, model_local])\n",
" subprocess.run([\"hdfs\", \"dfs\", \"-get\", model_info_hdfs, model_info_local])\n",
" \n",
" # 加载模型\n",
" model = joblib.load(model_local)\n",
" model_info = joblib.load(model_info_local)\n",
" \n",
" # 可选:清理临时文件\n",
" # os.remove(model_local)\n",
" # os.remove(model_info_local)\n",
" \n",
" return model, model_info\n",
"\n",
"# 模型测试函数\n",
"def test_model(model, X_test, y_test=None):\n",
" \"\"\"\n",
" 测试模型性能\n",
" \"\"\"\n",
" # 预测\n",
" y_pred = model.predict(X_test)\n",
" y_pred_proba = model.predict_proba(X_test)\n",
" \n",
" # 如果有真实标签,计算准确率\n",
" if y_test is not None:\n",
" from sklearn.metrics import accuracy_score, classification_report\n",
" accuracy = accuracy_score(y_test, y_pred)\n",
" print(f\"准确率: {accuracy:.4f}\")\n",
" print(\"\\n分类报告:\")\n",
" print(classification_report(y_test, y_pred))\n",
" \n",
" return y_pred, y_pred_proba\n",
"\n",
"hdfs_path = \"hdfs://harunasg/home/byte_data_rec_content_sg_training/tiktok_proactive_publish_instance/wy_test/xgboost_attribution_model_v3\"\n",
"\n",
"try:\n",
" # 加载模型(选择其中一种方法)\n",
" model, model_info = load_model_with_download(hdfs_path)\n",
" # 或者\n",
" # model, model_info = load_model_with_download(hdfs_path)\n",
" \n",
" print(\"模型加载成功!\")\n",
" print(f\"模型类型: {type(model)}\")\n",
" print(f\"模型参数: {model.get_params()}\")\n",
" print(f\"模型信息: {model_info}\")\n",
" \n",
" # 准备测试数据\n",
" # 这里需要根据你的实际数据格式来准备\n",
" # 示例:创建一些测试数据\n",
" np.random.seed(42)\n",
" X_test = np.random.randn(100, 26) # 假设有10个特征\n",
" y_test = np.random.randint(0, 2, 100) # 二分类标签\n",
" \n",
" # 测试模型\n",
" y_pred, y_pred_proba = test_model(model, X_test, y_test)\n",
" \n",
" # 查看预测结果\n",
" print(f\"\\n预测结果示例(前5个):\")\n",
" print(f\"预测类别: {y_pred[:5]}\")\n",
" print(f\"预测概率: {y_pred_proba[:5]}\")\n",
" \n",
" # 如果有特征名称,可以查看特征重要性\n",
" if hasattr(model, 'feature_importances_'):\n",
" feature_importance = model.feature_importances_\n",
" print(f\"\\n特征重要性: {feature_importance}\")\n",
" \n",
"except Exception as e:\n",
" print(f\"加载或测试模型时出错: {e}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# prep_feats_lbs 是一个 训练/验证样本构造器:\n",
"theme_mapping = {\n",
" 'Fine-grained thematic similarity': 1,\n",
" 'Unable to see': 2,\n",
" 'Irrelevant': 3,\n",
" 'General thematic similarity': 4,\n",
" 'All are just photos of a person/random shoot': 5,\n",
" 'Not my language': 6,\n",
" 'The two contents are completely the same': 7\n",
"}\n",
"\n",
"mean_value_mm = 0.5844145473966679\n",
"mean_value_visual = 0.6677746468989721\n",
"mean_value_text = 0.7259379792385305\n",
"mean_value_mmcf = 0.7186459371711221\n",
"mean_value_ocr = 0.7142993929646865\n",
"mean_value_asr = 0.8206938029243036\n",
"mean_value_rq = 0.7781203800338651\n",
"\n",
"def prep_feats_lbs(df, df_neg, fine_cnt=1063, is_train=True, POSITIVE_THEME_LABELS={1, 4}, NEGATIVE_THEME_LABELS={3}, rm_sup_tier=False, \\\n",
" feats_names=['mm_similarity'], only_manual=False, pos_ratio=0.16, keep_all_fine=False, abstract_keep_elements=2, filter_null_mm=False, max_pos_cnt=1000000000):\n",
" fine_cnt = 10000000000\n",
" ## 根据主题标签创建label\n",
" # 使用 map 函数创建新列\n",
" if 'similar_theme' in df.columns:\n",
" df['theme_label'] = df['similar_theme'].map(theme_mapping)\n",
" if keep_all_fine:\n",
" fine_cnt = 10000000000\n",
" else:\n",
" fine_cnt = (df['theme_label'] == 4).sum()\n",
" # 检查是否有未映射的值\n",
" unmapped_values = df[df['theme_label'].isna()]['similar_theme'].unique()\n",
" if len(unmapped_values) > 0:\n",
" print(f\"警告:发现未映射的值: {unmapped_values}\")\n",
" # 为未映射的值设置默认值:0\n",
" df['theme_label'] = df['theme_label'].fillna(0)\n",
"\n",
" # 添加随机负样本\n",
" if df_neg is not None:\n",
" if \"view_gid\" not in df_neg.columns:\n",
" df_neg['view_gid'] = df_neg['gid'] \n",
"\n",
" # 合并两列的mm_similarity值,计算均值\n",
" if filter_null_mm:\n",
" # 遍历df和df_neg,如果mm_similarity、visual_similarity、text_similarity、mmcf_similarity、ocr_similarity、asr_similarity、rq_similarity\n",
" # 定义需要检查的多模态相似度特征列\n",
" mm_feature_columns = [\n",
" 'mm_similarity', \n",
" 'visual_similarity', \n",
" 'text_similarity', \n",
" 'mmcf_similarity', \n",
" 'ocr_similarity', \n",
" 'asr_similarity', \n",
" 'rq_similarity'\n",
" ]\n",
" \n",
" # 只保留数据集中实际存在的列\n",
" existing_mm_columns = [col for col in mm_feature_columns if col in df.columns]\n",
" \n",
" if existing_mm_columns:\n",
" # 过滤df中所有多模态特征都不为空的行\n",
" df = df.dropna(subset=existing_mm_columns, how='any')\n",
" if df_neg is not None:\n",
" # 过滤df_neg中所有多模态特征都不为空的行\n",
" df_neg = df_neg.dropna(subset=existing_mm_columns, how='any')\n",
" \n",
" print(f\"过滤空值后,df剩余 {len(df)} 行,df_neg剩余 {len(df_neg)} 行\")\n",
" print(f\"检查的列包括: {existing_mm_columns}\")\n",
"\n",
"\n",
" global mean_value_mm\n",
" global mean_value_visual\n",
" global mean_value_text\n",
" global mean_value_mmcf\n",
" global mean_value_ocr\n",
" global mean_value_asr\n",
" global mean_value_rq\n",
" \n",
" if is_train:\n",
" combined_series_mm = pd.concat([df['mm_similarity'], df_neg['mm_similarity']], axis=0)\n",
" mean_value_mm = combined_series_mm.mean()\n",
" combined_series_visual = pd.concat([df['visual_similarity'], df_neg['visual_similarity']], axis=0)\n",
" mean_value_visual = combined_series_visual.mean()\n",
" combined_series_text = pd.concat([df['text_similarity'], df_neg['text_similarity']], axis=0)\n",
" mean_value_text = combined_series_text.mean()\n",
" combined_series_mmcf = pd.concat([df['mmcf_similarity'], df_neg['mmcf_similarity']], axis=0)\n",
" mean_value_mmcf = combined_series_mmcf.mean()\n",
" combined_series_ocr = pd.concat([df['ocr_similarity'], df_neg['ocr_similarity']], axis=0)\n",
" mean_value_ocr = combined_series_ocr.mean()\n",
" combined_series_asr = pd.concat([df['asr_similarity'], df_neg['asr_similarity']], axis=0)\n",
" mean_value_asr = combined_series_asr.mean()\n",
" combined_series_rq = pd.concat([df['rq_similarity'], df_neg['rq_similarity']], axis=0)\n",
" mean_value_rq = combined_series_rq.mean()\n",
"\n",
" print(f'mean_value_mm:{mean_value_mm}')\n",
" print(f'mean_value_visual:{mean_value_visual}')\n",
" print(f'mean_value_text:{mean_value_text}')\n",
" print(f'mean_value_mmcf:{mean_value_mmcf}')\n",
" print(f'mean_value_ocr:{mean_value_ocr}')\n",
" print(f'mean_value_asr:{mean_value_asr}')\n",
" print(f'mean_value_rq:{mean_value_rq}')\n",
"\n",
" if df_neg is not None:\n",
" null_count = df_neg['visual_similarity'].isna().sum()\n",
" print(f\"visual_similarity 列中的空值数量: {null_count}\")\n",
"\n",
" df['mm_similarity'] = df['mm_similarity'].fillna(mean_value_mm)\n",
" df['visual_similarity'] = df['visual_similarity'].fillna(mean_value_visual)\n",
" df['text_similarity'] = df['text_similarity'].fillna(mean_value_text)\n",
" df['mmcf_similarity'] = df['mmcf_similarity'].fillna(mean_value_mmcf)\n",
" df['ocr_similarity'] = df['ocr_similarity'].fillna(mean_value_ocr)\n",
" df['asr_similarity'] = df['asr_similarity'].fillna(mean_value_asr)\n",
" df['rq_similarity'] = df['rq_similarity'].fillna(mean_value_rq)\n",
"\n",
" man_feats, man_labels = [], []\n",
" man_lb1_feats, man_lb4_feats, man_ir_feats = [], [], []\n",
" man_rel_cnt, man_unrel_cnt = 0, 0\n",
" fine_grain_cnt = 0\n",
" ir_cnt = 0\n",
" total_pos_num = 0\n",
" for index, row in df.iterrows():\n",
" if rm_sup_tier:\n",
" if row['view_g_mt_diversity_tier3'] in [10071, 10005, 10080, 10073]:\n",
" continue\n",
" feature = []\n",
" for feat_name in feats_names:\n",
" feature.append(row[feat_name])\n",
"\n",
" if 'theme_label' in df.columns:\n",
" label = row['theme_label']\n",
"\n",
" if label in NEGATIVE_THEME_LABELS:\n",
" man_unrel_cnt += 1\n",
" man_feats.append(feature)\n",
" man_labels.append(0)\n",
" man_ir_feats.append(feature)\n",
" \n",
" elif label in POSITIVE_THEME_LABELS:\n",
" if label == 1:\n",
" fine_grain_cnt += 1\n",
" if fine_grain_cnt > fine_cnt:\n",
" continue\n",
" man_lb1_feats.append(feature)\n",
" elif label == 4:\n",
" # 抽象主题相似只保留相似元素个数大于1的样本\n",
" if abstract_keep_elements > 0:\n",
" similar_elements = str(row['similar_elements'])\n",
" if similar_elements is not None:\n",
" similar_elements = similar_elements.replace('[', '').replace(']', '').split(',')\n",
" else:\n",
" similar_elements = None\n",
" if len(similar_elements) >= 2:\n",
" man_feats.append(feature)\n",
" man_labels.append(1)\n",
" continue\n",
" else:\n",
" continue\n",
" man_lb4_feats.append(feature)\n",
"\n",
" man_rel_cnt += 1\n",
" man_feats.append(feature)\n",
" man_labels.append(1)\n",
" if man_rel_cnt > max_pos_cnt:\n",
" break\n",
" else:\n",
" continue\n",
" else:\n",
" label = row['target_label']\n",
" if label == 0:\n",
" man_unrel_cnt += 1\n",
" man_feats.append(feature)\n",
" man_labels.append(0)\n",
" man_ir_feats.append(feature)\n",
" else:\n",
" man_rel_cnt += 1\n",
" man_feats.append(feature)\n",
" man_labels.append(1)\n",
" print(\"人工打标训练样本,相关数量: \", man_rel_cnt, \"不相关数量: \", man_unrel_cnt)\n",
"\n",
" if only_manual:\n",
" return man_feats, man_labels\n",
" else:\n",
" neg_feats = []\n",
" neg_lbs = []\n",
" neg_unrel_cnt = 0\n",
" neg_rel_cnt = 0\n",
" neg_sample_cnt = man_rel_cnt / pos_ratio - man_unrel_cnt - man_rel_cnt\n",
" print(\"man_rel_cnt, pos_ratio, man_unrel_cnt, man_rel_cnt, neg_sample_cnt\")\n",
" print(man_rel_cnt, pos_ratio, man_unrel_cnt, man_rel_cnt, neg_sample_cnt)\n",
" df_neg['mm_similarity'] = df_neg['mm_similarity'].fillna(mean_value_mm)\n",
" df_neg['visual_similarity'] = df_neg['visual_similarity'].fillna(mean_value_visual)\n",
" df_neg['text_similarity'] = df_neg['text_similarity'].fillna(mean_value_text)\n",
" df_neg['mmcf_similarity'] = df_neg['mmcf_similarity'].fillna(mean_value_mmcf)\n",
" df_neg['ocr_similarity'] = df_neg['ocr_similarity'].fillna(mean_value_ocr)\n",
" df_neg['asr_similarity'] = df_neg['asr_similarity'].fillna(mean_value_asr)\n",
" df_neg['rq_similarity'] = df_neg['rq_similarity'].fillna(mean_value_rq)\n",
" print(\"before: neg_sample_cnt, neg_unrel_cnt\")\n",
" print(neg_sample_cnt, neg_unrel_cnt)\n",
" for index, row in df_neg.iterrows():\n",
" if index % 10000 == 0:\n",
" print(index)\n",
" if index > neg_sample_cnt:\n",
" break\n",
" feature = []\n",
" for feat_name in feats_names:\n",
" feature.append(row[feat_name])\n",
" # feature = [row['mm_similarity'], row['visual_similarity'], row['text_similarity'], row[\"mmcf_similarity\"], row[\"ocr_similarity\"], row[\"asr_similarity\"], row[\"rq_similarity\"], \\\n",
" # row['equal_tier'], float(row['view_general']), float(row['pub_general']), float(row['sup_view_general']), float(row['sup_pub_general']), \\\n",
" # row['view_group_id'], row['pub_group_id']]\n",
" label = 0\n",
" if label == 0:\n",
" neg_unrel_cnt += 1\n",
" neg_feats.append(feature)\n",
" neg_lbs.append(0)\n",
" elif label == 1:\n",
" neg_rel_cnt += 1\n",
" neg_feats.append(feature)\n",
" neg_lbs.append(1)\n",
" else:\n",
" continue\n",
" print(\"after: neg_sample_cnt, neg_unrel_cnt\")\n",
" print(neg_sample_cnt, neg_unrel_cnt)\n",
" rel_cnt = man_rel_cnt + neg_rel_cnt\n",
" unrel_cnt = man_unrel_cnt + neg_unrel_cnt\n",
" ral_ratio = rel_cnt * 1.0 / (rel_cnt + unrel_cnt)\n",
" features = man_feats + neg_feats\n",
" labels = man_labels + neg_lbs\n",
" print(\"相关数量: \", rel_cnt, \"不相关数量: \", unrel_cnt)\n",
" print(\"相比比例: {}\".format(ral_ratio))\n",
"\n",
" return features, labels, ral_ratio, man_lb1_feats, man_lb4_feats, man_ir_feats, neg_feats"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!hdfs dfs -get hdfs://harunasg/home/byte_data_tt_m/explicit_proactive_publish_dataset/xgboost_attribution_model_eval/embed_standard_evalset_new_feat_add_interest.csv"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": "# 增加兴趣点特征\n# interest_feats = [\"keywords_semantic_cluster_tier1_has_overlap\",\"keywords_semantic_cluster_tier1_overlap_cnt\", \"keywords_semantic_cluster_tier2_has_overlap\", \"keywords_semantic_cluster_tier2_overlap_cnt\", \"keywords_semantic_cluster_dedup_tier_has_overlap\",\"keywords_semantic_cluster_dedup_tier_overlap_cnt\",\"keywords_has_overlap\",\"keywords_overlap_cnt\"]\ninterest_feats = [\"keywords_semantic_cluster_tier1_has_overlap\",\"keywords_semantic_cluster_tier1_overlap_cnt\", \"keywords_semantic_cluster_tier2_has_overlap\", \"keywords_semantic_cluster_tier2_overlap_cnt\", \"keywords_semantic_cluster_dedup_tier_has_overlap\",\"keywords_semantic_cluster_dedup_tier_overlap_cnt\",\"keywords_has_overlap\",\"keywords_overlap_cnt\"]\n\n\nori_feats_names=['mm_similarity','visual_similarity','text_similarity','mmcf_similarity','ocr_similarity','asr_similarity','rq_similarity','equal_tier','view_general','pub_general','sup_view_general','sup_pub_general','sticker_intersect','equal_music_id','hashtag_iou','view_is_pgc','pub_is_pgc','equal_group_language']\n\nfeats_names = ori_feats_names+interest_feats\nprint(feats_names)\n\nPOSITIVE_THEME_LABELS = {1, 4}\nNEGATIVE_THEME_LABELS = {3}\nprint('202507-202510 训练样本添加特征情况:')\n\n# 人工标注样本:0702以及多语种样本\nembed_feat = pd.read_csv(\"embed_standard_evalset_new_feat_add_interest.csv\")\n\nembed_feat_neg = pd.read_csv(\"embed_standard_evalset_new_feat_add_interest.csv\")\n# df_train_q3_neg_all['is_choose'] = 0\nfeatures_processed, labels_processed = prep_feats_lbs(embed_feat, None, 1063, False, {1, 4}, {3}, feats_names=feats_names, keep_all_fine=True, abstract_keep_elements=2, pos_ratio=0.2, only_manual=True,filter_null_mm=True)\n\nfeature_filename = \"train_features_embed_standard_evalset_new_feat_add_interest.json\"\nlabel_filename = \"train_labels_embed_standard_evalset_new_feat_add_interest.json\"\n# 保存到文件\nwith open(feature_filename, 'w') as f:\n json.dump(features_processed, f)\n\nwith open(label_filename, 'w') as f:\n json.dump(labels_processed, f)\n!mkdir -p /mnt/bn/bohanzhainas1/jiashuo/active_proaction/xgboost_attribution_model_eval/\n!cp $feature_filename /mnt/bn/bohanzhainas1/jiashuo/active_proaction/xgboost_attribution_model_eval/\n!cp $label_filename /mnt/bn/bohanzhainas1/jiashuo/active_proaction/xgboost_attribution_model_eval/"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 读取时使用\n",
"with open('train_features_embed_standard_evalset_new_feat_add_interest.json', 'r') as f:\n",
" features_test_stand = json.load(f)\n",
"\n",
"with open('train_labels_embed_standard_evalset_new_feat_add_interest.json', 'r') as f:\n",
" labels_test_stand = json.load(f)\n",
"\n",
"\n",
"flag = '4tier_feat'\n",
"feats_te_lst = []\n",
"features_test = features_test_stand\n",
"labels_test = labels_test_stand\n",
"\n",
"for ele in features_test:\n",
" feat = ele\n",
" feats_te_lst.append(feat)\n",
"\n",
"model, model_info = load_model_with_download(hdfs_path)\n",
"\n",
"# 测试模型\n",
"y_pred, y_pred_proba = test_model(model, feats_te_lst, labels_test_stand)\n",
"\n",
"predict_results=clf_xgb_4tier_fe.predict(feats_te_lst)\n",
"conf_mat = confusion_matrix(labels_test, predict_results)\n",
"\n",
"print(conf_mat)\n",
"calculate_classification_report(conf_mat)\n",
"\n",
"predict_scores = model.predict_proba(feats_te_lst)\n",
"precision_xgb_4tier_fe, recall_xgb_4tier_fe, auc_xgb_4tier_fe = precision_recall(labels_test, predict_scores[:, 1])\n",
"\n",
"print(auc_xgb_4tier_fe)\n",
"\n",
"for i in range(len(precision_xgb_4tier_fe)):\n",
" if abs(precision_xgb_4tier_fe[i] - 0.80) < 0.01:\n",
" print(\"xgb_4tier_fe thres: \", np.linspace(0, 1, num=100)[i], \"recall: \", recall_xgb_4tier_fe[i], \"precision: \", precision_xgb_4tier_fe[i])\n",
"\n",
"\n",
"# 查看预测结果\n",
"print(f\"\\n预测结果示例(前5个):\")\n",
"print(f\"预测类别: {y_pred[:5]}\")\n",
"print(f\"预测概率: {y_pred_proba[:5]}\")\n",
"\n",
"# 如果有特征名称,可以查看特征重要性\n",
"if hasattr(model, 'feature_importances_'):\n",
" feature_importance = model.feature_importances_\n",
" print(f\"\\n特征重要性: {feature_importance}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"predict_results=clf_xgb_4tier_fe.predict(feats_te_lst)\n",
"conf_mat = confusion_matrix(labels_test, predict_results)\n",
"\n",
"print(conf_mat)\n",
"calculate_classification_report(conf_mat)\n",
"\n",
"predict_scores = clf_xgb_4tier_fe.predict_proba(feats_te_lst)\n",
"precision_xgb_4tier_fe, recall_xgb_4tier_fe, auc_xgb_4tier_fe = precision_recall(labels_test, predict_scores[:, 1])\n",
"\n",
"print(auc_xgb_4tier_fe)\n",
"\n",
"for i in range(len(precision_xgb_4tier_fe)):\n",
" if abs(precision_xgb_4tier_fe[i] - 0.8) < 0.01:\n",
" print(\"xgb_4tier_fe thres: \", np.linspace(0, 1, num=100)[i], \"recall: \", recall_xgb_4tier_fe[i], \"precision: \", precision_xgb_4tier_fe[i])\n"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 2
} |