File size: 64,636 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 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 | {
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": "# 这是一段 多模态特征在线获取 + 多线程推理 的通用工具脚本,核心用途:\n\n# 通过 UE (Universal Embedding) 和 Abase 两条通路,并发拉取同一条素材的 7 种模态向量(mm / visual / text / mmcf / ocr / asr / rq)。\n# 支持 HDFS 文件读写、指标打点、异常容错、多线程加速。\n# 为下游模型推理或特征工程提供 标准化输入。\n\nimport json\nimport bytedlogger\nimport tensorflow as tf\nimport numpy as np\n# from laplace import Laplace # unused\nimport bytedabase\nimport os\nimport concurrent.futures\nimport byted_tensorproto as tb\nfrom typing import IO, Any, List\nfrom contextlib import contextmanager\nimport subprocess\nimport cityhash\nfrom bytedance import metrics\nimport thriftpy2\nimport euler\nimport threading\nfrom tqdm import tqdm\n\nmetric_client = metrics.Client(prefix=\"tiktok.data.mmv3_cover_rate\")\n\nHADOOP_BIN = 'HADOOP_ROOT_LOGGER=ERROR,console /opt/tiger/yarn_deploy/hadoop/bin/hdfs'\n\ndef hexists(file_path: str) -> bool:\n \"\"\" hdfs capable to check whether a file_path is exists \"\"\"\n if file_path.startswith('hdfs'):\n return os.system(\"{} dfs -test -e {}\".format(HADOOP_BIN, file_path)) == 0\n return os.path.exists(file_path)\n\ndef hopen(hdfs_path: str, mode: str = \"r\") -> IO[Any]:\n is_hdfs = hdfs_path.startswith('hdfs')\n if is_hdfs:\n return hdfs_open(hdfs_path, mode)\n else:\n return open(hdfs_path, mode)\n\n@contextmanager # type: ignore\ndef hdfs_open(hdfs_path: str, mode: str = \"r\") -> IO[Any]:\n \"\"\" \n 打开一个 hdfs 文件, 用 contextmanager.\n\n Args:\n hfdfs_path (str): hdfs文件路径\n mode (str): 打开模式,支持 [\"r\", \"w\", \"wa\"]\n \"\"\"\n pipe = None\n if mode.startswith(\"r\"):\n pipe = subprocess.Popen(\n \"{} dfs -text {}\".format(HADOOP_BIN, hdfs_path), shell=True, stdout=subprocess.PIPE)\n yield pipe.stdout\n pipe.stdout.close() # type: ignore\n pipe.wait()\n return\n if mode == \"wa\" or mode == \"a\":\n pipe = subprocess.Popen(\n \"{} dfs -appendToFile - {}\".format(HADOOP_BIN, hdfs_path), shell=True, stdin=subprocess.PIPE)\n yield pipe.stdin\n pipe.stdin.close() # type: ignore\n pipe.wait()\n return\n if mode.startswith(\"w\"):\n pipe = subprocess.Popen(\n \"{} dfs -put -f - {}\".format(HADOOP_BIN, hdfs_path), shell=True, stdin=subprocess.PIPE)\n yield pipe.stdin\n pipe.stdin.close() # type: ignore\n pipe.wait()\n return\n raise RuntimeError(\"unsupported io mode: \" + mode)\n\n\ndef tb_decode(raw):\n if raw is None:\n return np.array([])\n t = tb.parse(raw)\n if t:\n return np.array(t[0])\n else:\n return np.array([])\n\n\nclass AbaseHandler:\n def __init__(self, psm, table_name, source='', timeout_ms=200, metrics_prefix='tiktok.data.mmv3_cover_rate'):\n self.abase_client = bytedabase.Client(psm=psm, table=table_name, timeout_ms=timeout_ms)\n self.source = source\n\n def get(self, object_id: int, version: int):\n key = str(object_id) + '_' + str(version) + '_' + self.source\n raw = self.abase_client.get(key)\n return raw\n\n def mget(self, object_ids: list, version: int = 1):\n keys = [str(oid) + '_' + str(version) + '_' + self.source for oid in object_ids]\n raw = self.abase_client.batch_get(keys)\n return raw\n\n\ndef multi_thread_fn(data, thread_num=20, region=\"row\"):\n results = dict()\n results_flag = dict()\n pbar = tqdm(total=len(data), desc=\"Processing items\")\n pbar_lock = threading.Lock()\n\n data_list = [[] for _ in range(thread_num)]\n for i, row in enumerate(data):\n data_list[i % thread_num].append(row)\n\n if region == \"row\":\n abase_psm = 'bytedance.abase2.tiktok_query_hashtag_v5'\n abase_table_name = 'ue_storage_table'\n abase_version = 2\n elif region == \"eu\":\n abase_psm = 'bytedance.abase2.tiktok_query_hashtag_eval'\n abase_table_name = 'ue_storage_table'\n abase_version = 1\n else:\n raise RuntimeError(f\"Invalid region {region}\")\n\n mm_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmpretrain_v3_mm_emb1')\n visual_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmpretrain_v3_visual_emb1')\n text_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmpretrain_v3_text_emb1')\n mmcf_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmcf_v3_mm_emb1')\n ocr_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmpretrain_v3_ocr_emb1')\n asr_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmpretrain_v3_asr_emb1')\n rq_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmcf_v3_rq_10x100_ids')\n mmv2_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=\"tiktok_multi_modal_embedding\", source='tiktok_mmpretrain_mm_emb')\n mmcfv2_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=\"tiktok_multi_modal_embedding\", source='tiktok_copair_emb')\n \n \n abases = {\"mm\": mm_emb_set_abase,\n \"visual\": visual_emb_set_abase,\n \"text\": text_emb_set_abase,\n \"mmcf\": mmcf_emb_set_abase,\n \"ocr\": ocr_emb_set_abase,\n \"asr\": asr_emb_set_abase,\n \"rq\": rq_emb_set_abase,\n \"mmv2\": mmv2_emb_set_abase,\n \"mmcfv2\": mmcfv2_emb_set_abase,\n \"version\": abase_version}\n\n def single_thread_fn_abase(tid, data):\n ret_flag = {}\n ret = {}\n for i, row in enumerate(data, 1):\n for key in abases.keys():\n if key == \"version\":\n continue\n try:\n object_id = int(row[\"item_id\"])\n emb = tb_decode(abases[key].get(object_id, abases[\"version\"]))\n ret[f\"{key}_{object_id}_embeds\"] = emb\n if not np.all(emb==0):\n ret_flag[f\"{key}_{object_id}_embeds\"] = 1 \n else:\n ret_flag[f\"{key}_{object_id}_embeds\"] = 0 #emb\n except Exception as e:\n pass\n with pbar_lock:\n pbar.update(1)\n results_flag[tid] = ret_flag\n results[tid] = ret\n \n threads = []\n for i in range(thread_num):\n # create a new thread and add it to the list\n thread = threading.Thread(target=single_thread_fn_abase, args=(i, data_list[i]))\n threads.append(thread)\n\n # start all the threads\n for thread in threads:\n thread.start()\n \n # wait for all the threads to finish\n for thread in threads:\n thread.join()\n pbar.close()\n \n return results, results_flag"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"### 验证 emb 是否可以正常取到\n",
"region = \"va\"\n",
"if region == \"va\":\n",
" abase_psm = 'bytedance.abase2.tiktok_multi_modal_embedding'\n",
" abase_table_name = 'tiktok_multi_modal_embedding_v3'\n",
" abase_version = 1\n",
"elif region == \"eu\":\n",
" abase_psm = 'bytedance.abase2.tiktok_query_hashtag_eval'\n",
" abase_table_name = 'ue_storage_table'\n",
" abase_version = 1\n",
"else:\n",
" raise RuntimeError(f\"Invalid region {region}\")\n",
"\n",
"mm_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmpretrain_v3_mm_emb1')\n",
"visual_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmpretrain_v3_visual_emb1')\n",
"text_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmpretrain_v3_text_emb1')\n",
"mmcf_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmcf_v3_mm_emb1')\n",
"ocr_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmpretrain_v3_ocr_emb1')\n",
"asr_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmpretrain_v3_asr_emb1')\n",
"rq_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=abase_table_name, source='tiktok_mmcf_v3_rq_10x100_ids')\n",
"mmv2_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=\"tiktok_multi_modal_embedding\", source='tiktok_mmpretrain_mm_emb')\n",
"mmcfv2_emb_set_abase = AbaseHandler(psm=abase_psm, table_name=\"tiktok_multi_modal_embedding\", source='tiktok_copair_emb')\n",
"\n",
"\n",
"abases = {\"mm\": mm_emb_set_abase,\n",
" \"visual\": visual_emb_set_abase,\n",
" \"text\": text_emb_set_abase,\n",
" \"mmcf\": mmcf_emb_set_abase,\n",
" \"ocr\": ocr_emb_set_abase,\n",
" \"asr\": asr_emb_set_abase,\n",
" \"rq\": rq_emb_set_abase,\n",
" # \"mmv2\": mmv2_emb_set_abase,\n",
" # \"mmcfv2\": mmcfv2_emb_set_abase,\n",
" \"version\": abase_version}\n",
"\n",
"\n",
"for key in abases.keys():\n",
" print(key)\n",
" if key == \"version\":\n",
" continue\n",
" try:\n",
" # object_id = int(7545218462969384206) # 0905\n",
" object_id = int(7534337356329995537) # 0911\n",
" # object_id = int(7532443774371384632) # 0912\n",
" # object_id = int(7555593347419622711) # 0913\n",
" print(object_id)\n",
" emb = tb_decode(abases[key].get(object_id, abases[\"version\"]))\n",
" print(emb)\n",
" # ret[f\"{key}_{object_id}_embeds\"] = emb\n",
" if not np.all(emb==0):\n",
" # ret_flag[f\"{key}_{object_id}_embeds\"] = 1 \n",
" print('ok')\n",
" else:\n",
" print('wrong')\n",
" # ret_flag[f\"{key}_{object_id}_embeds\"] = 0 #emb\n",
" except Exception as e:\n",
" print(e)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 这段代码是一个 离线特征工程脚本:\n",
"\n",
"# 读入包含 view / pub 两侧素材信息的 CSV;\n",
"# 通过 多线程 调用 multi_thread_inference_fn3 拉取 7 种模态的 UE 向量;\n",
"# 计算 余弦相似度 及 20 余种业务匹配特征(tier、hashtag、工具、音乐、语言等);\n",
"# 输出 可直接喂模型的宽表。\n",
"\n",
"import ast\n",
"import pandas as pd\n",
"import math\n",
"import numpy as np\n",
"from sklearn.metrics.pairwise import cosine_similarity\n",
"\n",
"GENERAL_TIER = [0,10075,10074,10083,10071,10005,10080,10009,10073,10029,10026,10025,10028,10027]\n",
"# 排除4个超大众垂类\n",
"SUP_GENERAL_TIER = [0,10071,10005,10080,10073]\n",
"\n",
"def split_list(data, max_thread_num):\n",
" \"\"\"\n",
" 将列表尽可能均匀地分割成多个子列表\n",
" \n",
" :param data: 原始列表\n",
" :param max_thread_num: 最大线程数/分割数\n",
" :return: 分割后的子列表组成的列表\n",
" \"\"\"\n",
" n = len(data)\n",
" chunk_size = math.ceil(n / max_thread_num) # 计算每个子列表的大小\n",
" return [data[i:i + chunk_size] for i in range(0, n, chunk_size)]\n",
"\n",
"def list_of_dicts_to_dict(results):\n",
" \"\"\"\n",
" 将列表中的字典合并为一个字典\n",
" 如果有重复键,后面的字典值会覆盖前面的\n",
" \n",
" :param results: 字典列表\n",
" :return: 合并后的字典\n",
" \"\"\"\n",
" merged_dict = {}\n",
" for d in results:\n",
" merged_dict.update(d)\n",
" return merged_dict\n",
"\n",
"def calculate_iou(list1, list2):\n",
" \"\"\"计算两个列表的IOU\"\"\"\n",
" set1 = set(list1)\n",
" set2 = set(list2)\n",
" \n",
" intersection = len(set1 & set2) # 交集大小\n",
" union = len(set1 | set2) # 并集大小\n",
" \n",
" return intersection / union if union != 0 else 0 # 避免除以0\n",
"\n",
"\n",
"def count_hashtag_intersect(view_tags, pub_tags):\n",
" \"\"\"计算两个hashtag列表的重合数量\"\"\"\n",
" \n",
" # 处理None或空列表的情况\n",
" if not view_tags and not pub_tags:\n",
" return -1 # 两列都没有值\n",
" \n",
" view_set = set(view_tags) if view_tags else set()\n",
" pub_set = set(pub_tags) if pub_tags else set()\n",
" \n",
" overlap_count = len(view_set & pub_set)\n",
" \n",
" # 根据重合数量判断匹配特征\n",
" if overlap_count >= 1:\n",
" return 1 # 至少有一个重合\n",
" else:\n",
" return 0 # 无重合或仅一列有值\n",
"\n",
"\n",
"def calculate_intersect_feature(row, view_col, pub_col, threshold=1):\n",
" \"\"\"\n",
" 通用计算两列工具/特征的交集匹配特征\n",
" -1: 两列都没有值\n",
" 0: 所有都不相等或只有一列有值\n",
" 1: 交集数量≥阈值\n",
" \"\"\"\n",
" view_val = str(row[view_col])\n",
" pub_val = str(row[pub_col])\n",
"\n",
" # 辅助函数:判断值是否为空\n",
" def is_empty(value):\n",
" if pd.isna(value): # 处理NaN、None\n",
" return True\n",
" if isinstance(value, str):\n",
" return value.strip() == '' or value.strip() == '0' or value.strip().lower() == 'nan'\n",
" if isinstance(value, (list, set, tuple)):\n",
" return len(value) == 0\n",
" return False\n",
" \n",
" if is_empty(view_val) and is_empty(pub_val):\n",
" return -1\n",
" \n",
" view_set = set(view_val.split(',')) if view_val != 'nan' else set()\n",
" pub_set = set(pub_val.split(',')) if pub_val != 'nan' else set()\n",
" \n",
" intersect_size = len(view_set & pub_set)\n",
" \n",
" return 1 if intersect_size >= threshold else 0\n",
"\n",
"total_emb_dct = {}\n",
"\n",
"### 计算UE相似度\n",
"def calc_uesim_feats_add_gmatch(file_path='Final_Deliverable_29_Apr_percent70_tier_0623.csv', col1='view_gid', col2='pub_gid', MAX_THREAD_NUM=30, is_test=False, sample_cnt=30000):\n",
" try:\n",
" df = pd.read_csv(file_path, encoding='utf-8-sig')\n",
" rows, columns = df.shape\n",
" if rows == 0:\n",
" print(\"错误:CSV文件不包含任何数据行\")\n",
" except FileNotFoundError:\n",
" print(\"错误:找不到{}文件,请确保文件已正确生成\".format(file_path))\n",
" except Exception as e:\n",
" print(f\"读取CSV文件时出错: {e}\") \n",
"\n",
" if is_test:\n",
" df = df.head(30).copy()\n",
" \n",
" if sample_cnt is not None:\n",
" df = df.head(sample_cnt).copy()\n",
" # 转换view_gid列为列表\n",
" view_gid_list = [{\"item_id\": item} for item in df[col1].unique()]\n",
" pub_gid_list = [{\"item_id\": item} for item in df[col2].unique()]\n",
" print(f'len of unique {col1}, {len(view_gid_list)}')\n",
" print(f'len of unique {col2}, {len(pub_gid_list)}')\n",
"\n",
" view_data_list = split_list(view_gid_list, MAX_THREAD_NUM)\n",
" pub_data_list = split_list(pub_gid_list, MAX_THREAD_NUM)\n",
" results_view, results_view_flag = multi_thread_inference_fn3(view_data_list)\n",
" results_pub, results_pub_flag = multi_thread_inference_fn3(pub_data_list) \n",
" results_pub_dict = list_of_dicts_to_dict(results_pub)\n",
" results_view_dict = list_of_dicts_to_dict(results_view)\n",
"\n",
" merged_dict = results_pub_dict.copy()\n",
" merged_dict.update(results_view_dict)\n",
" file_name = file_path.split('.')[0]\n",
" total_emb_dct[file_name] = merged_dict\n",
"\n",
" print(f'len of results_pub_flag: {len(results_pub_flag)}, len of results_view_flag: {len(results_view_flag)}')\n",
" \n",
" df[col1] = df[col1].astype(str)\n",
" df[col2] = df[col2].astype(str)\n",
"\n",
" # 定义前缀列表\n",
" prefixes = [\"mm\", \"visual\", \"text\", \"mmcf\", \"ocr\", \"asr\", \"rq\"]\n",
" # 为每种前缀创建相似度计算函数\n",
" def calculate_similarity_for_prefix(prefix, view_id, pub_id):\n",
" # 构造完整的key\n",
" view_key = f\"{prefix}_{view_id}_embeds\"\n",
" pub_key = f\"{prefix}_{pub_id}_embeds\"\n",
" # 获取embedding\n",
" view_emb = results_view_dict.get(view_key)\n",
" pub_emb = results_pub_dict.get(pub_key)\n",
"\n",
" # 检查是否存在\n",
" if view_emb is None or pub_emb is None:\n",
" return np.nan\n",
" # 转换为numpy数组并计算相似度\n",
" view_emb = np.array(view_emb).reshape(1, -1)\n",
" pub_emb = np.array(pub_emb).reshape(1, -1)\n",
"\n",
" cos_sim = cosine_similarity(view_emb, pub_emb)[0][0]\n",
" # print(f'cos_sim: {cos_sim}')\n",
"\n",
" return cos_sim\n",
" \n",
" # 为每种前缀添加相似度列\n",
" for prefix in prefixes:\n",
" col_name = f\"{prefix}_similarity\"\n",
" df[col_name] = df.apply(\n",
" lambda row: calculate_similarity_for_prefix(prefix, row[col1], row[col2]),\n",
" axis=1\n",
" )\n",
" \n",
" df['equal_tier'] = df.apply(lambda row: 1 if row['view_g_mt_diversity_tier3'] == row['pub_g_mt_diversity_tier3'] else 0, axis=1)\n",
" df['view_general'] = df.apply(lambda row: 1 if row['view_g_mt_diversity_tier3'] in GENERAL_TIER else 0, axis=1)\n",
" df['pub_general'] = df.apply(lambda row: 1 if row['pub_g_mt_diversity_tier3'] in GENERAL_TIER else 0, axis=1)\n",
" df['sup_view_general'] = df.apply(lambda row: 1 if row['view_g_mt_diversity_tier3'] in SUP_GENERAL_TIER else 0, axis=1)\n",
" df['sup_pub_general'] = df.apply(lambda row: 1 if row['pub_g_mt_diversity_tier3'] in SUP_GENERAL_TIER else 0, axis=1)\n",
" df['has_intelabel_intersec'] = df.apply(\n",
" lambda row: len(set(row['view_keywords_semantic_cluster_dedup_tier']) \n",
" & set(row['pub_keywords_semantic_cluster_dedup_tier'])) > 0,\n",
" axis=1\n",
" )\n",
"\n",
" # hashtag 是否有交集\n",
" df['view_hashtag_names'] = df['view_hashtag_names'].apply(ast.literal_eval) # 默认存储str,这里将其还原为 str list,坑...\n",
" df['pub_hashtag_names'] = df['pub_hashtag_names'].apply(ast.literal_eval)\n",
" \n",
" df['hashtag_intersect'] = df.apply(lambda row: count_hashtag_intersect(\n",
" row['view_hashtag_names'], \n",
" row['pub_hashtag_names']\n",
" ), \n",
" axis=1)\n",
"\n",
" df['hashtag_iou'] = df.apply(\n",
" lambda row: calculate_iou(\n",
" row['view_hashtag_names'], \n",
" row['pub_hashtag_names']\n",
" ),\n",
" axis=1\n",
" )\n",
"\n",
" # 编辑工具是否有交集\n",
" df['creation_intersect'] = df.apply(\n",
" lambda row: calculate_intersect_feature(\n",
" row, view_col='view_all_creation_used_functions', pub_col='pub_all_creation_used_functions', threshold=3\n",
" ), \n",
" axis=1\n",
" )\n",
"\n",
" # df['view_all_creation_used_functions'] = df['view_all_creation_used_functions'].astype(str)\n",
" # df['pub_all_creation_used_functions'] = df['pub_all_creation_used_functions'].astype(str)\n",
" # df['creation_intersect'] = df.apply(\n",
" # lambda row: len(\n",
" # set(row['view_all_creation_used_functions'].split(',')) & \n",
" # set(row['pub_all_creation_used_functions'].split(','))\n",
" # ) > 0,\n",
" # axis=1\n",
" # )\n",
"\n",
" # 高编工具是否有交集\n",
" df['pro_creation_intersect'] = df.apply(\n",
" lambda row: calculate_intersect_feature(\n",
" row, view_col='view_all_editor_pro_used_functions', pub_col='pub_all_editor_pro_used_functions', threshold=1 # 可自定义阈值\n",
" ), \n",
" axis=1\n",
" )\n",
"\n",
" # df['view_all_editor_pro_used_functions'] = df['view_all_editor_pro_used_functions'].astype(str)\n",
" # df['pub_all_editor_pro_used_functions'] = df['pub_all_editor_pro_used_functions'].astype(str)\n",
" # df['pro_creation_intersect'] = df.apply(\n",
" # lambda row: len(\n",
" # set(row['view_all_editor_pro_used_functions'].split(',')) & \n",
" # set(row['pub_all_editor_pro_used_functions'].split(','))\n",
" # ) > 0,\n",
" # axis=1\n",
" # )\n",
"\n",
" # 特效是否有交集\n",
" df['sticker_intersect'] = df.apply(\n",
" lambda row: calculate_intersect_feature(row, view_col='view_sticker', pub_col='pub_sticker', threshold=1), axis=1\n",
" )\n",
"\n",
" df['equal_music_id'] = np.where(df['view_music_id'].astype(str) == df['pub_music_id'].astype(str), 1, 0)\n",
"\n",
" df['equal_original_caption_lang'] = np.where(df['view_original_caption_lang'].astype(str) == df['pub_original_caption_lang'].astype(str), 1, 0)\n",
" \n",
" df['equal_selected_asr_lang'] = np.where(df['view_selected_asr_lang'].astype(str) == df['pub_selected_asr_lang'].astype(str), 1, 0)\n",
"\n",
" df['equal_content_type'] = np.where(df['view_content_type'].astype(str) == df['pub_content_type'].astype(str), 1, 0)\n",
"\n",
" df['equal_group_language'] = np.where(df['view_group_language'].astype(str) == df['pub_group_language'].astype(str), 1, 0)\n",
"\n",
" # 是否含有配音\n",
" df['equal_has_original_audio'] = np.where(df['view_has_original_audio'] == df['pub_has_original_audio'], 1, 0)\n",
"\n",
" df['view_is_long_video'] = np.where(df['view_real_duration'] > 60, 1, 0)\n",
" df['pub_is_long_video'] = np.where(df['pub_real_duration'] > 60, 1, 0)\n",
"\n",
" return df"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def write_to_csv(df, file_name='dfq2_train_tier_ten_expensive.csv'):\n",
" try:\n",
" df.to_csv(file_name, index=False, encoding='utf-8-sig')\n",
" print(\"数据已成功写入 {} 文件\".format(file_name))\n",
" except Exception as e:\n",
" print(f\"写入CSV文件时出错: {e}\") "
]
},
{
"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/new_tier_evalset/new_tier_evalset_210_112_0306_03_output_feat.csv"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = pd.read_csv('new_tier_evalset_210_112_0306_03_output_feat.csv')\n",
"df.head(10)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df_labeled_tier = calc_uesim_feats_add_gmatch('new_tier_evalset_210_112_0306_03_output_feat.csv', 'view_gid', 'pub_gid', is_test=False, sample_cnt=None)\n",
"out_file_name = \"embed_new_tier_evalset_210_112_0306_03_output_feat.csv\"\n",
"write_to_csv(df_labeled_tier, out_file_name)\n",
"# hdfs rm removed - using local path now\n",
"!mkdir -p /mnt/bn/bohanzhainas1/jiashuo/active_proaction/xgboost_attribution_model_eval/ && cp $out_file_name /mnt/bn/bohanzhainas1/jiashuo/active_proaction/xgboost_attribution_model_eval/"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df_labeled_tier[['view_g_mt_diversity_tier3', 'pub_g_mt_diversity_tier3', 'view_keywords_semantic_cluster_tier1', 'pub_keywords_semantic_cluster_tier1', 'view_keywords_semantic_cluster_tier2', 'pub_keywords_semantic_cluster_tier2']].head(20)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import ast\n",
"import pandas as pd\n",
"\n",
"def safe_string_to_list(str_data):\n",
" \"\"\"安全地将格式为 '[1, 2, 3]' 的字符串转换为列表\"\"\"\n",
" if pd.isna(str_data) or not str_data or str_data.strip() == '[]' or str_data.strip() == '':\n",
" return []\n",
" try:\n",
" return ast.literal_eval(str_data)\n",
" except (ValueError, SyntaxError):\n",
" return []\n",
"\n",
"def flatten_and_filter(items):\n",
" \"\"\"展平嵌套列表并过滤无效值\"\"\"\n",
" result = []\n",
" for item in items:\n",
" if isinstance(item, list):\n",
" # 递归展平嵌套列表\n",
" result.extend(flatten_and_filter(item))\n",
" elif isinstance(item, int):\n",
" if item >= 0:\n",
" result.append(item)\n",
" elif item not in [-1, -100000001]:\n",
" result.append(item)\n",
" return result\n",
"\n",
"def add_overlap_features(input_file=\"test.csv\", output_file=None):\n",
" \"\"\"\n",
" 向CSV文件追加4个特征(每个key对应的view和pub列表是否有交集)\n",
" \n",
" 参数:\n",
" input_file: 输入CSV文件路径\n",
" output_file: 输出CSV文件路径(None则覆盖原文件)\n",
" \"\"\"\n",
" # 读取数据\n",
" df = pd.read_csv(input_file)\n",
" \n",
" # 定义要处理的key列表\n",
" keys = ['keywords_semantic_cluster_tier1', \n",
" 'keywords_semantic_cluster_tier2', \n",
" 'keywords_semantic_cluster_dedup_tier', \n",
" 'keywords']\n",
" \n",
" # 为每个key计算交集特征\n",
" for key in keys:\n",
" # 构建列名\n",
" view_col = f'view_{key}'\n",
" pub_col = f'pub_{key}'\n",
" \n",
" # 确保列存在\n",
" if view_col not in df.columns or pub_col not in df.columns:\n",
" print(f\"警告: {view_col} 或 {pub_col} 不存在,跳过\")\n",
" continue\n",
" \n",
" # 计算是否有交集\n",
" has_overlap_list = []\n",
" overlap_count_list = []\n",
" \n",
" for idx, row in df.iterrows():\n",
" try:\n",
" # 处理view列\n",
" view_data = row[view_col]\n",
" if isinstance(view_data, str):\n",
" view_list = safe_string_to_list(view_data)\n",
" else:\n",
" view_list = view_data if isinstance(view_data, list) else []\n",
" \n",
" # 处理pub列\n",
" pub_data = row[pub_col]\n",
" if isinstance(pub_data, str):\n",
" pub_list = safe_string_to_list(pub_data)\n",
" else:\n",
" pub_list = pub_data if isinstance(pub_data, list) else []\n",
" \n",
" # 展平并过滤无效值\n",
" view_filtered = flatten_and_filter(view_list)\n",
" pub_filtered = flatten_and_filter(pub_list)\n",
" \n",
" # 转换为集合,处理不可哈希类型\n",
" try:\n",
" view_set = set(view_filtered)\n",
" pub_set = set(pub_filtered)\n",
" except TypeError:\n",
" # 如果有不可哈希类型,转换为字符串\n",
" view_set = set(str(x) for x in view_filtered)\n",
" pub_set = set(str(x) for x in pub_filtered)\n",
" \n",
" # 判断是否有交集和计算交集数量\n",
" intersection = view_set & pub_set\n",
" has_overlap = len(intersection) > 0\n",
" overlap_count = len(intersection)\n",
" \n",
" has_overlap_list.append(int(has_overlap))\n",
" overlap_count_list.append(overlap_count)\n",
" \n",
" except Exception as e:\n",
" print(f\"处理第 {idx} 行时出错: {e}\")\n",
" has_overlap_list.append(0)\n",
" overlap_count_list.append(0)\n",
" \n",
" # 添加新特征列\n",
" has_overlap_col = f'{key}_has_overlap'\n",
" overlap_cnt_col = f'{key}_overlap_cnt'\n",
" \n",
" df[has_overlap_col] = has_overlap_list\n",
" df[overlap_cnt_col] = overlap_count_list\n",
" \n",
" # 打印统计信息\n",
" intersection_count = sum(has_overlap_list)\n",
" total_overlap = sum(overlap_count_list)\n",
" print(f\"{key}:\")\n",
" print(f\" {has_overlap_col}: 有交集的行数={intersection_count}, 占比={intersection_count/len(df):.2%}\")\n",
" print(f\" {overlap_cnt_col}: 总交集元素数={total_overlap}, 平均={total_overlap/len(df):.2f}\")\n",
" \n",
" # 保存结果\n",
" if output_file is None:\n",
" return df\n",
" output_file = input_file\n",
" \n",
" df.to_csv(output_file, index=False)\n",
" print(f\"\\n处理完成,结果已保存到: {output_file}\")\n",
" print(f\"新增了 {len(keys)*2} 个特征列\")\n",
" \n",
" return df\n",
"\n",
"# 使用\n",
"# df = pd.read_csv(\"embed_feat_test.csv\")\n",
"# df = add_overlap_features(\"embed_feat_test.csv\", \"embed_feat_test_interest4.csv\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"input_file = \"embed_new_tier_evalset_210_112_0306_03_output_feat.csv\"\n",
"output_file = \"embed_new_tier_evalset_210_112_0306_03_output_feat_add_interest.csv\"\n",
"df = add_overlap_features(input_file, output_file)\n",
"# hdfs rm removed - using local path now\n",
"!mkdir -p /mnt/bn/bohanzhainas1/jiashuo/active_proaction/xgboost_attribution_model_eval/new_tier_evalset/ && cp $output_file /mnt/bn/bohanzhainas1/jiashuo/active_proaction/xgboost_attribution_model_eval/new_tier_evalset/"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 检查数据的空值情况\n",
"def generate_null_report(filename, top_n=20, check_empty_lists=True):\n",
" \"\"\"\n",
" 生成详细的空值(NaN/None/NaT)和空列表统计报告\n",
" \n",
" Parameters:\n",
" -----------\n",
" df : pandas.DataFrame\n",
" 输入的数据框\n",
" top_n : int, default=20\n",
" 显示空值最多的前N列\n",
" check_empty_lists : bool, default=True\n",
" 是否检查空列表(包括字符串形式的\"[]\")\n",
" \n",
" Returns:\n",
" --------\n",
" dict\n",
" 包含详细统计信息的字典\n",
" \"\"\"\n",
" import numpy as np\n",
" df = pd.read_csv(filename)\n",
" \n",
" total_rows = len(df)\n",
" \n",
" # 计算标准空值数量(包括NaN、None、NaT等)\n",
" null_counts = df.isnull().sum()\n",
" non_null_counts = df.notnull().sum()\n",
" null_percentages = (null_counts / total_rows * 100).round(2) if total_rows > 0 else 0\n",
" \n",
" # 计算空列表数量(如果启用)\n",
" empty_list_counts = pd.Series([0] * len(df.columns), index=df.columns)\n",
" empty_list_percentages = pd.Series([0] * len(df.columns), index=df.columns)\n",
" \n",
" if check_empty_lists:\n",
" for col in df.columns:\n",
" # 检查每个值是否为列表且为空\n",
" is_empty_list = df[col].apply(lambda x: \n",
" # 情况1: Python空列表对象\n",
" (isinstance(x, list) and len(x) == 0) or\n",
" # 情况2: 字符串形式的\"[]\"(从CSV读取时可能出现)\n",
" (isinstance(x, str) and x.strip() == '[]') or\n",
" # 情况3: 字符串形式的\"[]\"可能有空格\n",
" (isinstance(x, str) and x.strip() == '[] ') or\n",
" (isinstance(x, str) and x.strip() == ' []')\n",
" )\n",
" empty_list_counts[col] = is_empty_list.sum()\n",
" empty_list_percentages[col] = (empty_list_counts[col] / total_rows * 100).round(2) if total_rows > 0 else 0\n",
" \n",
" # 计算总空值(标准空值 + 空列表)\n",
" total_empty_counts = null_counts + empty_list_counts\n",
" total_empty_percentages = (total_empty_counts / total_rows * 100).round(2) if total_rows > 0 else 0\n",
" \n",
" # 获取数据类型\n",
" dtypes = df.dtypes\n",
" \n",
" # 创建结果DataFrame\n",
" report = pd.DataFrame({\n",
" 'Column': df.columns,\n",
" 'Data_Type': dtypes.values,\n",
" 'Standard_Null_Count': null_counts.values,\n",
" 'Standard_Null_Percentage': null_percentages.values,\n",
" 'Empty_List_Count': empty_list_counts.values,\n",
" 'Empty_List_Percentage': empty_list_percentages.values,\n",
" 'Total_Empty_Count': total_empty_counts.values,\n",
" 'Total_Empty_Percentage': total_empty_percentages.values,\n",
" 'Non_Empty_Count': (total_rows - total_empty_counts).values,\n",
" 'Total_Rows': total_rows,\n",
" 'Sample_Value': df.iloc[0] if total_rows > 0 else [np.nan] * len(df.columns)\n",
" })\n",
" \n",
" # 按总空值数量降序排序\n",
" report = report.sort_values('Total_Empty_Count', ascending=False).reset_index(drop=True)\n",
" \n",
" # 生成报告输出\n",
" print(\"=\" * 100)\n",
" print(\"📊 空值和空列表统计报告\")\n",
" print(\"=\" * 100)\n",
" print(f\"数据集形状: {df.shape} (行×列)\")\n",
" print(f\"总行数: {total_rows:,}\")\n",
" print(f\"总列数: {len(df.columns)}\")\n",
" print(f\"检查空列表: {'是' if check_empty_lists else '否'}\")\n",
" print(\"=\" * 100)\n",
" \n",
" # 整体统计\n",
" total_null_cells = null_counts.sum()\n",
" total_empty_list_cells = empty_list_counts.sum() if check_empty_lists else 0\n",
" total_empty_cells = total_null_cells + total_empty_list_cells\n",
" total_cells = total_rows * len(df.columns)\n",
" \n",
" overall_null_percentage = (total_null_cells / total_cells * 100).round(2) if total_cells > 0 else 0\n",
" overall_empty_list_percentage = (total_empty_list_cells / total_cells * 100).round(2) if total_cells > 0 else 0\n",
" overall_empty_percentage = (total_empty_cells / total_cells * 100).round(2) if total_cells > 0 else 0\n",
" \n",
" print(f\"总单元格数: {total_cells:,}\")\n",
" print(f\"标准空值单元格总数: {total_null_cells:,} ({overall_null_percentage}%)\")\n",
" if check_empty_lists:\n",
" print(f\"空列表单元格总数: {total_empty_list_cells:,} ({overall_empty_list_percentage}%)\")\n",
" print(f\"总空单元格数: {total_empty_cells:,} ({overall_empty_percentage}%)\")\n",
" print(f\"完全无空值的列数: {(total_empty_counts == 0).sum()}\")\n",
" print(f\"有空值的列数: {(total_empty_counts > 0).sum()}\")\n",
" print(f\"完全为空的列数: {(total_empty_counts == total_rows).sum()}\")\n",
" print(\"=\" * 100)\n",
" \n",
" if total_empty_counts.sum() > 0:\n",
" print(f\"\\n🔝 前{top_n}个空值最多的列:\")\n",
" print(\"-\" * 100)\n",
" \n",
" # 创建简化显示的表\n",
" display_cols = ['Column', 'Data_Type', 'Total_Empty_Count', \n",
" 'Total_Empty_Percentage', 'Standard_Null_Percentage']\n",
" \n",
" if check_empty_lists:\n",
" display_cols.append('Empty_List_Percentage')\n",
" \n",
" display_df = report[display_cols].head(top_n).copy()\n",
" \n",
" # 格式化显示\n",
" pd.set_option('display.max_colwidth', 25)\n",
" pd.set_option('display.float_format', '{:.2f}'.format)\n",
" \n",
" # 重命名列名以便更好显示\n",
" column_names = {\n",
" 'Column': '列名',\n",
" 'Data_Type': '数据类型',\n",
" 'Total_Empty_Count': '总空值数',\n",
" 'Total_Empty_Percentage': '总空值比例%',\n",
" 'Standard_Null_Percentage': '标准空值%',\n",
" 'Empty_List_Percentage': '空列表%'\n",
" }\n",
" display_df = display_df.rename(columns=column_names)\n",
" \n",
" print(display_df.to_string(index=False))\n",
" pd.reset_option('display.max_colwidth')\n",
" pd.reset_option('display.float_format')\n",
" else:\n",
" print(\"\\n✅ 数据集中没有空值!\")\n",
" \n",
" print(\"\\n\" + \"=\" * 100)\n",
" print(\"📈 空值分布统计:\")\n",
" print(\"-\" * 100)\n",
" \n",
" # 空值比例分布统计\n",
" bins = [0, 0.1, 1, 5, 10, 20, 50, 100]\n",
" bin_labels = ['0%', '0-0.1%', '0.1-1%', '1-5%', '5-10%', '10-20%', '20-50%', '50-100%']\n",
" \n",
" distribution = {}\n",
" for i in range(len(bins)-1):\n",
" mask = (total_empty_percentages >= bins[i]) & (total_empty_percentages < bins[i+1])\n",
" count = mask.sum()\n",
" distribution[bin_labels[i]] = count\n",
" \n",
" # 100%空值的列单独统计\n",
" fully_empty = (total_empty_percentages == 100).sum()\n",
" distribution['100%'] = fully_empty\n",
" \n",
" print(\"总空值比例分布:\")\n",
" for range_label, count in distribution.items():\n",
" if count > 0:\n",
" print(f\" {range_label}: {count}列\")\n",
" \n",
" print(\"\\n\" + \"=\" * 100)\n",
" print(\"💡 详细分析和建议:\")\n",
" print(\"-\" * 100)\n",
" \n",
" # 找出不同类型的空值\n",
" if check_empty_lists and empty_list_counts.sum() > 0:\n",
" # 找出只有空列表的列\n",
" only_empty_lists = report[(report['Empty_List_Count'] > 0) & (report['Standard_Null_Count'] == 0)]\n",
" if len(only_empty_lists) > 0:\n",
" print(f\"📋 仅包含空列表的列 ({len(only_empty_lists)}列):\")\n",
" for _, row in only_empty_lists.head(5).iterrows():\n",
" print(f\" - {row['Column']}: {row['Empty_List_Count']}个空列表 ({row['Empty_List_Percentage']}%)\")\n",
" if len(only_empty_lists) > 5:\n",
" print(f\" ... 还有{len(only_empty_lists)-5}列\")\n",
" \n",
" # 找出主要是字符串形式空列表的列\n",
" if empty_list_counts.sum() > 0:\n",
" print(f\"\\n🔍 空列表类型分析:\")\n",
" for col in df.columns:\n",
" if empty_list_counts[col] > 0:\n",
" # 采样检查空列表的类型\n",
" sample_values = df[col].head(10)\n",
" string_empty_count = sum(isinstance(x, str) and x.strip() == '[]' for x in sample_values if pd.notnull(x))\n",
" list_empty_count = sum(isinstance(x, list) and len(x) == 0 for x in sample_values if pd.notnull(x))\n",
" \n",
" if string_empty_count > 0 or list_empty_count > 0:\n",
" print(f\" {col}: {string_empty_count}个字符串'[]', {list_empty_count}个Python空列表对象\")\n",
" \n",
" # 找出只有标准空值的列\n",
" only_standard_nulls = report[(report['Standard_Null_Count'] > 0) & (report['Empty_List_Count'] == 0)]\n",
" if len(only_standard_nulls) > 0:\n",
" print(f\"\\n📋 仅包含标准空值的列 ({len(only_standard_nulls)}列):\")\n",
" for _, row in only_standard_nulls.head(5).iterrows():\n",
" print(f\" - {row['Column']}: {row['Standard_Null_Count']}个标准空值 ({row['Standard_Null_Percentage']}%)\")\n",
" if len(only_standard_nulls) > 5:\n",
" print(f\" ... 还有{len(only_standard_nulls)-5}列\")\n",
" \n",
" # 找出两者都有的列\n",
" both_types = report[(report['Standard_Null_Count'] > 0) & (report['Empty_List_Count'] > 0)]\n",
" if len(both_types) > 0:\n",
" print(f\"\\n📋 同时包含两种空值的列 ({len(both_types)}列):\")\n",
" for _, row in both_types.head(5).iterrows():\n",
" print(f\" - {row['Column']}: {row['Standard_Null_Count']}个标准空值 + {row['Empty_List_Count']}个空列表\")\n",
" if len(both_types) > 5:\n",
" print(f\" ... 还有{len(both_types)-5}列\")\n",
" \n",
" # 根据空值情况给出建议\n",
" if fully_empty > 0:\n",
" print(f\"\\n⚠️ 发现 {fully_empty} 列完全为空,建议删除这些列\")\n",
" fully_empty_cols = report[report['Total_Empty_Percentage'] == 100]['Column'].tolist()\n",
" print(f\" 列名: {fully_empty_cols}\")\n",
" \n",
" high_empty_cols = report[report['Total_Empty_Percentage'] > 50]['Column'].head(5).tolist()\n",
" if high_empty_cols:\n",
" print(f\"\\n⚠️ 以下列空值超过50%,需要重点关注:\")\n",
" for col in high_empty_cols:\n",
" total_percent = report[report['Column'] == col]['Total_Empty_Percentage'].values[0]\n",
" std_percent = report[report['Column'] == col]['Standard_Null_Percentage'].values[0]\n",
" list_percent = report[report['Column'] == col]['Empty_List_Percentage'].values[0] if check_empty_lists else 0\n",
" print(f\" - {col}: {total_percent}% (标准空值: {std_percent}%, 空列表: {list_percent}%)\")\n",
" \n",
" # 额外的空列表处理建议\n",
" if check_empty_lists and empty_list_counts.sum() > 0:\n",
" print(f\"\\n💡 关于空列表的处理建议:\")\n",
" print(f\" 1. 如果空列表表示'无数据',可以考虑将其转换为标准NaN\")\n",
" print(f\" 2. 如果空列表是有效值(表示'空集合'),可以保留\")\n",
" print(f\" 3. 字符串形式的'[]'可以转换为Python空列表对象:df['列名'] = df['列名'].apply(lambda x: [] if isinstance(x, str) and x.strip() == '[]' else x)\")\n",
" \n",
" print(\"\\n\" + \"=\" * 100)\n",
" \n",
" # 返回详细报告\n",
" return {\n",
" 'report_df': report,\n",
" 'summary': {\n",
" 'total_rows': total_rows,\n",
" 'total_columns': len(df.columns),\n",
" 'total_cells': total_cells,\n",
" 'total_standard_null': total_null_cells,\n",
" 'total_empty_lists': total_empty_list_cells,\n",
" 'total_empty': total_empty_cells,\n",
" 'fully_empty_columns': fully_empty,\n",
" 'columns_with_any_empty': (total_empty_counts > 0).sum(),\n",
" 'check_empty_lists': check_empty_lists\n",
" }\n",
" }\n",
"\n",
"\n",
"# 辅助函数:专门检查空列表\n",
"def check_empty_lists_specific(df, specific_columns=None):\n",
" \"\"\"\n",
" 专门检查指定列中的空列表情况\n",
" \n",
" Parameters:\n",
" -----------\n",
" df : pandas.DataFrame\n",
" 输入的数据框\n",
" specific_columns : list or None, default=None\n",
" 要检查的列名列表,如果为None则检查所有列\n",
" \n",
" Returns:\n",
" --------\n",
" pandas.DataFrame\n",
" 包含空列表详细统计的DataFrame\n",
" \"\"\"\n",
" if specific_columns is None:\n",
" specific_columns = df.columns\n",
" \n",
" results = []\n",
" \n",
" for col in specific_columns:\n",
" if col in df.columns:\n",
" # 检查各种形式的空列表\n",
" is_empty = df[col].apply(lambda x: \n",
" # Python空列表对象\n",
" (isinstance(x, list) and len(x) == 0) or\n",
" # 字符串形式的\"[]\"(可能有空格)\n",
" (isinstance(x, str) and x.strip().replace(' ', '') == '[]')\n",
" )\n",
" \n",
" empty_count = is_empty.sum()\n",
" total_count = len(df[col])\n",
" empty_percent = (empty_count / total_count * 100).round(2) if total_count > 0 else 0\n",
" \n",
" # 获取一些示例\n",
" empty_examples = []\n",
" non_empty_examples = []\n",
" \n",
" for idx, val in enumerate(df[col].head(5)):\n",
" if idx < 3 and is_empty.iloc[idx]:\n",
" empty_examples.append(f\"行{idx}: {repr(val)}\")\n",
" elif idx < 3 and not is_empty.iloc[idx] and pd.notnull(val):\n",
" non_empty_examples.append(f\"行{idx}: {repr(val)}\")\n",
" \n",
" results.append({\n",
" 'Column': col,\n",
" 'Data_Type': str(df[col].dtype),\n",
" 'Total_Count': total_count,\n",
" 'Empty_List_Count': empty_count,\n",
" 'Empty_List_Percentage': empty_percent,\n",
" 'Empty_Examples': ', '.join(empty_examples[:2]),\n",
" 'Non_Empty_Examples': ', '.join(non_empty_examples[:2])\n",
" })\n",
" \n",
" return pd.DataFrame(results).sort_values('Empty_List_Count', ascending=False)\n",
"\n",
"\n",
"\n",
"\n",
"# 使用示例\n",
"# report = generate_null_report(\"feat_data_en_es_br_merge_202509_202510_filter_v2.csv\", top_n=50, check_empty_lists=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"report = generate_null_report(\"embed_new_tier_evalset_210_112_0306_03_output_feat_add_interest.csv\", top_n=50, check_empty_lists=True)"
]
},
{
"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",
" 'Same lipsync/dance with same music/challenge/meme': 8,\n",
" 'Irrelevant-Ads or AIGC': 9\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": [
"# 增加兴趣点特征\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\"]\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\"]\n",
"\n",
"\n",
"ori_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",
"\n",
"feats_names = ori_feats_names+interest_feats\n",
"print(feats_names)\n",
"\n",
"POSITIVE_THEME_LABELS = {1, 4}\n",
"NEGATIVE_THEME_LABELS = {3}\n",
"print('202507-202510 训练样本添加特征情况:')\n",
"\n",
"# 人工标注样本:0702以及多语种样本\n",
"embed_feat = pd.read_csv(\"embed_new_tier_evalset_210_112_0306_03_output_feat_add_interest.csv\")\n",
"\n",
"embed_feat_neg = pd.read_csv(\"embed_new_tier_evalset_210_112_0306_03_output_feat_add_interest.csv\")\n",
"# df_train_q3_neg_all['is_choose'] = 0\n",
"features_processed, labels_processed = prep_feats_lbs(embed_feat, None, 1063, False, {1, 4, 8}, {3, 9}, feats_names=feats_names, keep_all_fine=True, abstract_keep_elements=2, pos_ratio=0.2, only_manual=True,filter_null_mm=True)\n",
"\n",
"feature_filename = \"test_feats_new_tier_evalset_210_112_0306_03_add_interest.json\"\n",
"label_filename = \"test_labels_new_tier_evalset_210_112_0306_03_add_interest.json\"\n",
"# 保存到文件\n",
"with open(feature_filename, 'w') as f:\n",
" json.dump(features_processed, f)\n",
"\n",
"with open(label_filename, 'w') as f:\n",
" json.dump(labels_processed, f)\n",
"# hdfs rm removed - using local path now\n",
"!cp $feature_filename /mnt/bn/bohanzhainas1/jiashuo/active_proaction/xgboost_attribution_model_eval/new_tier_evalset/\n",
"# hdfs rm removed - using local path now\n",
"!cp $label_filename /mnt/bn/bohanzhainas1/jiashuo/active_proaction/xgboost_attribution_model_eval/new_tier_evalset/\n"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 2
} |