{"id":3897,"date":"2025-09-13T22:21:39","date_gmt":"2025-09-13T14:21:39","guid":{"rendered":"http:\/\/viplao.com\/?p=3897"},"modified":"2025-09-13T22:21:41","modified_gmt":"2025-09-13T14:21:41","slug":"%e3%80%90python%e5%ae%9e%e8%b7%b5%e6%a1%88%e4%be%8b%e3%80%91%e7%94%b5%e5%95%86%e5%b9%b3%e5%8f%b0%e6%95%b0%e6%8d%ae%e5%88%86%e6%9e%90%e5%92%8c%e6%8c%96%e6%8e%98-%e6%ac%ba%e8%af%88%e8%a1%8c%e4%b8%ba","status":"publish","type":"post","link":"http:\/\/viplao.com\/index.php\/2025\/09\/13\/%e3%80%90python%e5%ae%9e%e8%b7%b5%e6%a1%88%e4%be%8b%e3%80%91%e7%94%b5%e5%95%86%e5%b9%b3%e5%8f%b0%e6%95%b0%e6%8d%ae%e5%88%86%e6%9e%90%e5%92%8c%e6%8c%96%e6%8e%98-%e6%ac%ba%e8%af%88%e8%a1%8c%e4%b8%ba\/","title":{"rendered":"\u3010Python\u5b9e\u8df5\u6848\u4f8b\u3011\u7535\u5546\u5e73\u53f0\u6570\u636e\u5206\u6790\u548c\u6316\u6398 &#8211;  \u6b3a\u8bc8\u884c\u4e3a\u68c0\u6d4b"},"content":{"rendered":"\n<p>\u8be5\u811a\u672c\u5c06\u5305\u542b\u4ee5\u4e0b\u529f\u80fd\uff1a\u4f7f\u7528\u968f\u673a\u68ee\u6797\uff08Random Forest\uff09\u8fdb\u884c\u6709\u76d1\u7763\u7684\u6b3a\u8bc8\u68c0\u6d4b<\/p>\n\n\n\n<ol>\n<li>\u6a21\u62df\u751f\u6210\u5305\u542b\u6b63\u5e38\u4ea4\u6613\u548c\u6b3a\u8bc8\u4ea4\u6613\u7684\u7535\u5546\u4ea4\u6613\u6570\u636e\u3002<\/li>\n\n\n\n<li>\u8fdb\u884c\u6570\u636e\u9884\u5904\u7406\uff0c\u5305\u62ec\u5904\u7406\u7f3a\u5931\u503c\u3001\u7279\u5f81\u7f16\u7801\u548c\u521b\u5efa\u65b0\u7279\u5f81\u3002<\/li>\n\n\n\n<li>\u4f7f\u7528\u5b64\u7acb\u68ee\u6797\uff08Isolation Forest\uff09\u548c\u5c40\u90e8\u5f02\u5e38\u56e0\u5b50\uff08Local Outlier Factor\uff09\u4e24\u79cd\u65e0\u76d1\u7763\u5b66\u4e60\u7b97\u6cd5\u8fdb\u884c\u5f02\u5e38\u68c0\u6d4b\u3002<\/li>\n\n\n\n<li>\u4f7f\u7528\u968f\u673a\u68ee\u6797\uff08Random Forest\uff09\u8fdb\u884c\u6709\u76d1\u7763\u7684\u6b3a\u8bc8\u68c0\u6d4b\u3002<\/li>\n\n\n\n<li>\u8bc4\u4f30\u6a21\u578b\u6027\u80fd\uff0c\u5e76\u6bd4\u8f83\u4e0d\u540c\u65b9\u6cd5\u7684\u6548\u679c\u3002<\/li>\n\n\n\n<li>\u8bc6\u522b\u6b3a\u8bc8\u4ea4\u6613\u7684\u5173\u952e\u7279\u5f81\u3002<\/li>\n\n\n\n<li>\u751f\u6210\u4e00\u4efd\u5305\u542b\u5206\u6790\u8fc7\u7a0b\u3001\u7ed3\u679c\u548c\u5efa\u8bae\u7684\u7efc\u5408\u62a5\u544a\u3002<\/li>\n<\/ol>\n\n\n\n<p><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import IsolationForest, RandomForestClassifier\nfrom sklearn.neighbors import LocalOutlierFactor\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, confusion_matrix, classification_report\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom datetime import datetime, timedelta\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# --- \u914d\u7f6e ---\nNUM_TRANSACTIONS = 10000\nFRAUD_RATIO = 0.05  # 5% \u7684\u6b3a\u8bc8\u4ea4\u6613\nREPORT_PREFIX = '\u7535\u5546\u6b3a\u8bc8\u68c0\u6d4b\u62a5\u544a'\nRANDOM_SEED = 42\n\n# --- \u6570\u636e\u751f\u6210 ---\n\ndef generate_sample_fraud_data(n_transactions, fraud_ratio):\n    \"\"\"\u751f\u6210\u6a21\u62df\u7684\u7535\u5546\u4ea4\u6613\u6570\u636e\uff0c\u5305\u542b\u6b63\u5e38\u548c\u6b3a\u8bc8\u4ea4\u6613\"\"\"\n    print(\"--- \u6b63\u5728\u751f\u6210\u6a21\u62df\u4ea4\u6613\u6570\u636e ---\")\n    np.random.seed(RANDOM_SEED)\n    \n    data = &#91;]\n    transaction_ids = &#91;f'trans_{i}' for i in range(1, n_transactions + 1)]\n    \n    n_fraud = int(n_transactions * fraud_ratio)\n    n_normal = n_transactions - n_fraud\n    print(f\"\u751f\u6210 {n_normal} \u7b14\u6b63\u5e38\u4ea4\u6613 \u548c {n_fraud} \u7b14\u6b3a\u8bc8\u4ea4\u6613...\")\n    \n    for i in range(n_transactions):\n        is_fraud = 1 if i &lt; n_fraud else 0\n        \n        # --- \u57fa\u7840\u4ea4\u6613\u4fe1\u606f ---\n        user_id = f'user_{np.random.randint(1, n_transactions \/\/ 10)}' # \u5047\u8bbe\u7528\u6237\u6570\u662f\u4ea4\u6613\u6570\u76841\/10\n        product_id = f'prod_{np.random.randint(1, 1000)}'\n        amount = np.random.lognormal(7, 1.5) # \u4ea4\u6613\u91d1\u989d (\u5bf9\u6570\u6b63\u6001\u5206\u5e03)\n        timestamp = datetime.now() - timedelta(days=np.random.randint(0, 365), seconds=np.random.randint(0, 86400))\n        \n        # --- \u7528\u6237\u884c\u4e3a\u7279\u5f81 ---\n        # \u7528\u6237\u5386\u53f2\u4ea4\u6613\u6b21\u6570\u548c\u603b\u91d1\u989d\n        user_tx_count = np.random.poisson(20) if not is_fraud else np.random.poisson(5)\n        user_total_spent = np.random.lognormal(9, 1.0) if not is_fraud else np.random.lognormal(7, 1.5)\n        \n        # \u7528\u6237\u5e73\u5747\u4ea4\u6613\u91d1\u989d\n        user_avg_amount = user_total_spent \/ max(user_tx_count, 1)\n        \n        # --- \u8bbe\u5907\u548c\u5730\u7406\u4f4d\u7f6e\u7279\u5f81 ---\n        device_id = f'device_{np.random.randint(1, 5000)}'\n        ip_address = f\"192.168.{np.random.randint(0, 255)}.{np.random.randint(0, 255)}\"\n        \n        # \u5730\u7406\u4f4d\u7f6e (\u7b80\u5316\u4e3a\u56fd\u5bb6\u548c\u57ce\u5e02ID)\n        country = np.random.choice(&#91;'CN', 'US', 'UK', 'JP'], p=&#91;0.6, 0.2, 0.1, 0.1])\n        city_id = np.random.randint(1, 100)\n        \n        # --- \u6b3a\u8bc8\u6a21\u5f0f\u6a21\u62df ---\n        if is_fraud:\n            # \u6b3a\u8bc8\u4ea4\u6613\u53ef\u80fd\u5177\u6709\u7684\u7279\u5f81\n            # 1. \u91d1\u989d\u5f02\u5e38\u9ad8\n            if np.random.random() &lt; 0.3:\n                amount *= np.random.uniform(2, 10)\n            \n            # 2. \u77ed\u65f6\u95f4\u5185\u591a\u6b21\u4ea4\u6613 (Velocity)\n            if np.random.random() &lt; 0.4:\n                # \u8fd9\u91cc\u7b80\u5316\u5904\u7406\uff0c\u5728\u6570\u636e\u751f\u6210\u65f6\u65e0\u6cd5\u5b8c\u5168\u6a21\u62df\u65f6\u95f4\u5e8f\u5217\uff0c\u4f46\u5728\u7279\u5f81\u5de5\u7a0b\u4e2d\u53ef\u4ee5\u4f53\u73b0\n                pass \n            \n            # 3. \u65b0\u8bbe\u5907\/\u65b0IP\n            if np.random.random() &lt; 0.5:\n                device_id = f'device_fraud_{np.random.randint(10000, 20000)}' # \u4f7f\u7528\u4e00\u4e2a\u770b\u8d77\u6765\u50cf\u65b0\u8bbe\u5907\u7684ID\n                ip_address = f\"10.{np.random.randint(0, 255)}.{np.random.randint(0, 255)}.{np.random.randint(0, 255)}\"\n\n            # 4. \u8de8\u5730\u533a\u4ea4\u6613 (\u7528\u6237\u5e38\u7528\u5730\u533a vs \u672c\u6b21\u4ea4\u6613\u5730\u533a)\n            # \u7b80\u5316\uff1a\u5047\u8bbe\u6b3a\u8bc8\u4ea4\u6613\u66f4\u53ef\u80fd\u6765\u81ea\u4e0d\u540c\u56fd\u5bb6\n            if np.random.random() &lt; 0.4:\n                 country = np.random.choice(&#91;'RU', 'BR', 'IN']) # \u6a21\u62df\u9ad8\u98ce\u9669\u56fd\u5bb6\n            \n            # 5. \u7528\u6237\u884c\u4e3a\u5f02\u5e38 (\u4f8b\u5982\uff0c\u65b0\u7528\u6237\u5927\u989d\u4ea4\u6613)\n            if np.random.random() &lt; 0.3:\n                user_tx_count = np.random.poisson(1) # \u65b0\u7528\u6237\n                user_total_spent = amount # \u603b\u91d1\u989d\u5c31\u662f\u672c\u6b21\u4ea4\u6613\u91d1\u989d\n\n        data.append({\n            'transaction_id': transaction_ids&#91;i],\n            'user_id': user_id,\n            'product_id': product_id,\n            'amount': round(amount, 2),\n            'timestamp': timestamp,\n            'user_tx_count': user_tx_count,\n            'user_total_spent': round(user_total_spent, 2),\n            'user_avg_amount': round(user_avg_amount, 2),\n            'device_id': device_id,\n            'ip_address': ip_address,\n            'country': country,\n            'city_id': city_id,\n            'is_fraud': is_fraud\n        })\n        \n    df = pd.DataFrame(data)\n    \n    # --- \u884d\u751f\u7279\u5f81\u5de5\u7a0b (\u5728\u6570\u636e\u751f\u6210\u540e\u8fdb\u884c) ---\n    print(\"\u6b63\u5728\u8fdb\u884c\u7279\u5f81\u5de5\u7a0b...\")\n    df&#91;'timestamp'] = pd.to_datetime(df&#91;'timestamp'])\n    \n    # 1. \u65f6\u95f4\u7279\u5f81\n    df&#91;'hour_of_day'] = df&#91;'timestamp'].dt.hour\n    df&#91;'day_of_week'] = df&#91;'timestamp'].dt.dayofweek\n    \n    # 2. \u7528\u6237\u884c\u4e3a\u504f\u5dee\u7279\u5f81\n    df&#91;'amount_to_user_avg_ratio'] = df&#91;'amount'] \/ (df&#91;'user_avg_amount'] + 1e-8) # \u907f\u514d\u9664\u4ee5\u96f6\n    \n    # 3. \u901f\u5ea6\u7279\u5f81 (\u6bcf\u4e2a\u7528\u6237\u6bcf\u5c0f\u65f6\u4ea4\u6613\u6b21\u6570) - \u7b80\u5316\u6a21\u62df\n    user_hourly_counts = df.groupby(&#91;'user_id', pd.Grouper(key='timestamp', freq='H')]).size().reset_index(name='tx_per_hour')\n    df = df.merge(user_hourly_counts, on=&#91;'user_id', 'timestamp'], how='left')\n    df&#91;'tx_per_hour'].fillna(0, inplace=True)\n    \n    # 4. \u8bbe\u5907\/IP\u65b0\u9c9c\u5ea6 (\u5047\u8bbe\u6709\u4e00\u4e2a\u8bb0\u5f55\u9996\u6b21\u51fa\u73b0\u65f6\u95f4\u7684\u8868\uff0c\u8fd9\u91cc\u7b80\u5316\u4e3a\u662f\u5426\u662f\u65b0\u8bbe\u5907)\n    # \u7b80\u5316\u5904\u7406\uff1a\u5982\u679cdevice_id\u5305\u542b'fraud'\u5219\u8ba4\u4e3a\u662f\u65b0\u8bbe\u5907\n    df&#91;'is_new_device'] = df&#91;'device_id'].str.contains('fraud').astype(int)\n    \n    csv_filename = f'{REPORT_PREFIX}_\u6a21\u62df\u6570\u636e.csv'\n    df.to_csv(csv_filename, index=False, encoding='utf-8-sig')\n    print(f\"\u6a21\u62df\u6570\u636e\u5df2\u751f\u6210\u5e76\u4fdd\u5b58\u81f3: {csv_filename}\")\n    return df\n\n# --- \u6570\u636e\u9884\u5904\u7406 ---\n\ndef preprocess_data(df):\n    \"\"\"\u6570\u636e\u9884\u5904\u7406\"\"\"\n    print(\"\\n--- \u6b63\u5728\u8fdb\u884c\u6570\u636e\u9884\u5904\u7406 ---\")\n    df_processed = df.copy()\n    \n    # 1. \u7f16\u7801\u5206\u7c7b\u53d8\u91cf\n    le_country = LabelEncoder()\n    df_processed&#91;'country_encoded'] = le_country.fit_transform(df_processed&#91;'country'])\n    \n    # 2. \u9009\u62e9\u7528\u4e8e\u5efa\u6a21\u7684\u7279\u5f81\u5217 (\u6392\u9664ID\u548c\u6807\u7b7e)\n    feature_columns = &#91;\n        'amount', 'user_tx_count', 'user_total_spent', 'user_avg_amount',\n        'country_encoded', 'city_id', 'hour_of_day', 'day_of_week',\n        'amount_to_user_avg_ratio', 'tx_per_hour', 'is_new_device'\n    ]\n    \n    X = df_processed&#91;feature_columns]\n    y = df_processed&#91;'is_fraud']\n    \n    print(f\"\u9884\u5904\u7406\u5b8c\u6210\u3002\u7279\u5f81\u77e9\u9635\u5f62\u72b6: {X.shape}, \u6807\u7b7e\u5411\u91cf\u5f62\u72b6: {y.shape}\")\n    # \u6253\u5370\u7c7b\u522b\u5206\u5e03\n    print(f\"\u6b3a\u8bc8\u4ea4\u6613\u6570\u91cf: {y.sum()}, \u5360\u6bd4: {y.mean():.2%}\")\n    return X, y, le_country, feature_columns\n\n# --- \u65e0\u76d1\u7763\u5f02\u5e38\u68c0\u6d4b ---\n\ndef perform_unsupervised_detection(X, y):\n    \"\"\"\u6267\u884c\u65e0\u76d1\u7763\u5f02\u5e38\u68c0\u6d4b\"\"\"\n    print(\"\\n--- \u6b63\u5728\u6267\u884c\u65e0\u76d1\u7763\u5f02\u5e38\u68c0\u6d4b ---\")\n    results = {}\n    \n    # --- 1. Isolation Forest ---\n    print(\"\u8bad\u7ec3 Isolation Forest \u6a21\u578b...\")\n    # \u6ce8\u610f\uff1aIsolationForest\u9884\u6d4b1\u4e3a\u6b63\u5e38\uff0c-1\u4e3a\u5f02\u5e38\uff0c\u9700\u8981\u8f6c\u6362\n    iso_forest = IsolationForest(contamination=0.05, random_state=RANDOM_SEED, n_estimators=100)\n    iso_forest.fit(X)\n    y_pred_iso = iso_forest.predict(X)\n    y_pred_iso = np.where(y_pred_iso == -1, 1, 0) # \u8f6c\u6362\u4e3a 1 (\u6b3a\u8bc8), 0 (\u6b63\u5e38)\n    \n    results&#91;'Isolation Forest'] = {\n        'predictions': y_pred_iso,\n        'accuracy': accuracy_score(y, y_pred_iso),\n        'precision': precision_score(y, y_pred_iso, zero_division=0),\n        'recall': recall_score(y, y_pred_iso),\n        'f1': f1_score(y, y_pred_iso),\n        'auc': roc_auc_score(y, y_pred_iso) if len(np.unique(y_pred_iso)) &gt; 1 else 0.0\n    }\n    \n    # --- 2. Local Outlier Factor ---\n    print(\"\u8bad\u7ec3 Local Outlier Factor \u6a21\u578b...\")\n    # LOF\u4e0d\u9700\u8981\u663e\u5f0f\u8bad\u7ec3\uff0c\u76f4\u63a5fit_predict\n    lof = LocalOutlierFactor(n_neighbors=20, contamination=0.05)\n    y_pred_lof = lof.fit_predict(X)\n    y_pred_lof_scores = -lof.negative_outlier_factor_ # \u83b7\u53d6\u5f02\u5e38\u8bc4\u5206\n    y_pred_lof = np.where(y_pred_lof == -1, 1, 0) # \u8f6c\u6362\u4e3a 1 (\u6b3a\u8bc8), 0 (\u6b63\u5e38)\n    \n    results&#91;'Local Outlier Factor'] = {\n        'predictions': y_pred_lof,\n        'scores': y_pred_lof_scores, # \u4fdd\u7559\u8bc4\u5206\u7528\u4e8e\u53ef\u80fd\u7684\u9608\u503c\u8c03\u6574\n        'accuracy': accuracy_score(y, y_pred_lof),\n        'precision': precision_score(y, y_pred_lof, zero_division=0),\n        'recall': recall_score(y, y_pred_lof),\n        'f1': f1_score(y, y_pred_lof),\n        'auc': roc_auc_score(y, y_pred_lof) if len(np.unique(y_pred_lof)) &gt; 1 else 0.0\n    }\n    \n    # --- \u62a5\u544a ---\n    print(\"\\n--- \u65e0\u76d1\u7763\u6a21\u578b\u6027\u80fd\u5bf9\u6bd4 ---\")\n    unsup_comparison_df = pd.DataFrame({\n        'Model': list(results.keys()),\n        'Accuracy': &#91;results&#91;k]&#91;'accuracy'] for k in results.keys()],\n        'Precision': &#91;results&#91;k]&#91;'precision'] for k in results.keys()],\n        'Recall': &#91;results&#91;k]&#91;'recall'] for k in results.keys()],\n        'F1-Score': &#91;results&#91;k]&#91;'f1'] for k in results.keys()],\n        'AUC-ROC': &#91;results&#91;k]&#91;'auc'] for k in results.keys()]\n    })\n    print(unsup_comparison_df.round(4).to_string(index=False))\n    \n    return results\n\n# --- \u6709\u76d1\u7763\u6b3a\u8bc8\u68c0\u6d4b ---\n\ndef perform_supervised_detection(X, y):\n    \"\"\"\u6267\u884c\u6709\u76d1\u7763\u6b3a\u8bc8\u68c0\u6d4b\"\"\"\n    print(\"\\n--- \u6b63\u5728\u6267\u884c\u6709\u76d1\u7763\u6b3a\u8bc8\u68c0\u6d4b ---\")\n    \n    # \u5212\u5206\u8bad\u7ec3\u96c6\u548c\u6d4b\u8bd5\u96c6 (\u6a21\u62df\u5728\u7ebf\u5b66\u4e60\uff0c\u7528\u5386\u53f2\u6570\u636e\u8bad\u7ec3\uff0c\u65b0\u6570\u636e\u6d4b\u8bd5)\n    # \u4e3a\u4e86\u6f14\u793a\uff0c\u6211\u4eec\u7b80\u5355\u5730\u5212\u5206\u6570\u636e\u96c6\n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=RANDOM_SEED, stratify=y)\n    \n    # \u7279\u5f81\u7f29\u653e\n    scaler = StandardScaler()\n    X_train_scaled = scaler.fit_transform(X_train)\n    X_test_scaled = scaler.transform(X_test)\n    \n    # --- Random Forest Classifier ---\n    print(\"\u8bad\u7ec3 Random Forest \u6a21\u578b...\")\n    model_rf = RandomForestClassifier(n_estimators=100, random_state=RANDOM_SEED, class_weight='balanced', n_jobs=-1) # \u5904\u7406\u7c7b\u522b\u4e0d\u5e73\u8861\n    model_rf.fit(X_train_scaled, y_train)\n    y_pred_rf = model_rf.predict(X_test_scaled)\n    y_pred_proba_rf = model_rf.predict_proba(X_test_scaled)&#91;:, 1]\n    \n    results = {\n        'Random Forest': {\n            'model': model_rf,\n            'scaler': scaler,\n            'predictions': y_pred_rf,\n            'probabilities': y_pred_proba_rf,\n            'accuracy': accuracy_score(y_test, y_pred_rf),\n            'precision': precision_score(y_test, y_pred_rf),\n            'recall': recall_score(y_test, y_pred_rf),\n            'f1': f1_score(y_test, y_pred_rf),\n            'auc': roc_auc_score(y_test, y_pred_proba_rf),\n            'y_test': y_test # \u4fdd\u5b58\u6d4b\u8bd5\u6807\u7b7e\u7528\u4e8e\u62a5\u544a\n        }\n    }\n    \n    # --- \u62a5\u544a ---\n    rf_metrics = results&#91;'Random Forest']\n    print(f\"\\n--- Random Forest \u6a21\u578b\u6027\u80fd ---\")\n    print(f\"Accuracy:  {rf_metrics&#91;'accuracy']:.4f}\")\n    print(f\"Precision: {rf_metrics&#91;'precision']:.4f}\")\n    print(f\"Recall:    {rf_metrics&#91;'recall']:.4f}\")\n    print(f\"F1-Score:  {rf_metrics&#91;'f1']:.4f}\")\n    print(f\"AUC-ROC:   {rf_metrics&#91;'auc']:.4f}\")\n    \n    # \u7ed8\u5236\u6df7\u6dc6\u77e9\u9635\n    cm = confusion_matrix(rf_metrics&#91;'y_test'], rf_metrics&#91;'predictions'])\n    plt.figure(figsize=(8, 6))\n    sns.heatmap(cm, annot=True, fmt='d', cmap='Reds', \n                xticklabels=&#91;'Normal', 'Fraud'], \n                yticklabels=&#91;'Normal', 'Fraud'])\n    plt.title('\u6df7\u6dc6\u77e9\u9635 - Random Forest')\n    plt.xlabel('\u9884\u6d4b\u6807\u7b7e')\n    plt.ylabel('\u771f\u5b9e\u6807\u7b7e')\n    cm_path = f'{REPORT_PREFIX}_\u6df7\u6dc6\u77e9\u9635_RandomForest.png'\n    plt.savefig(cm_path)\n    plt.close()\n    print(f\"\u6df7\u6dc6\u77e9\u9635\u56fe\u8868\u5df2\u4fdd\u5b58\u81f3: {cm_path}\")\n    \n    # \u6253\u5370\u8be6\u7ec6\u5206\u7c7b\u62a5\u544a\n    print(\"\\n--- Random Forest \u8be6\u7ec6\u5206\u7c7b\u62a5\u544a ---\")\n    print(classification_report(rf_metrics&#91;'y_test'], rf_metrics&#91;'predictions'], target_names=&#91;'Normal', 'Fraud']))\n    \n    return results, cm_path\n\n# --- \u7279\u5f81\u91cd\u8981\u6027\u5206\u6790 ---\n\ndef analyze_feature_importance(model, feature_names, model_name):\n    \"\"\"\u5206\u6790\u5e76\u53ef\u89c6\u5316\u7279\u5f81\u91cd\u8981\u6027\"\"\"\n    print(f\"\\n--- \u5206\u6790 {model_name} \u7279\u5f81\u91cd\u8981\u6027 ---\")\n    \n    if hasattr(model, 'feature_importances_'):\n        importances = model.feature_importances_\n        indices = np.argsort(importances)&#91;::-1]\n        title = f'{model_name} - \u7279\u5f81\u91cd\u8981\u6027'\n    else:\n        print(\"\u6a21\u578b\u4e0d\u652f\u6301\u7279\u5f81\u91cd\u8981\u6027\u5206\u6790\u3002\")\n        return None, None\n\n    # \u521b\u5efa\u7279\u5f81\u91cd\u8981\u6027DataFrame\n    feature_importance_df = pd.DataFrame({\n        'feature': &#91;feature_names&#91;i] for i in indices],\n        'importance': &#91;importances&#91;i] for i in indices]\n    })\n    \n    print(\"\u7279\u5f81\u91cd\u8981\u6027\u6392\u5e8f:\")\n    print(feature_importance_df.head(10).to_string(index=False))\n\n    # \u7ed8\u5236\u7279\u5f81\u91cd\u8981\u6027\n    plt.figure(figsize=(10, 6))\n    sns.barplot(data=feature_importance_df.head(10), x='importance', y='feature', palette='viridis')\n    plt.title(title)\n    plt.xlabel('\u91cd\u8981\u6027')\n    plt.tight_layout()\n    feat_imp_path = f'{REPORT_PREFIX}_\u7279\u5f81\u91cd\u8981\u6027_{model_name.replace(\" \", \"_\")}.png'\n    plt.savefig(feat_imp_path)\n    plt.close()\n    print(f\"\u7279\u5f81\u91cd\u8981\u6027\u56fe\u8868\u5df2\u4fdd\u5b58\u81f3: {feat_imp_path}\")\n    \n    return feature_importance_df, feat_imp_path\n\n# --- \u62a5\u544a\u751f\u6210 ---\n\ndef generate_fraud_detection_report(unsup_results, sup_results, cm_path, feat_imp_df, feat_imp_path):\n    \"\"\"\u751f\u6210\u6700\u7ec8\u7684\u6b3a\u8bc8\u68c0\u6d4b\u5206\u6790\u62a5\u544a\"\"\"\n    print(\"\\n--- \u6b63\u5728\u751f\u6210\u6b3a\u8bc8\u68c0\u6d4b\u5206\u6790\u62a5\u544a ---\")\n    from datetime import datetime\n    report_filename = f\"{REPORT_PREFIX}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt\"\n    \n    sup_metrics = sup_results&#91;'Random Forest']\n    \n    with open(report_filename, 'w', encoding='utf-8') as f:\n        f.write(\"=\" * 50 + \"\\n\")\n        f.write(\"        \u7535\u5546\u5e73\u53f0\u7528\u6237\u98ce\u9669\u7ba1\u7406\u548c\u6b3a\u8bc8\u884c\u4e3a\u68c0\u6d4b\u62a5\u544a\\n\")\n        f.write(f\"        \u751f\u6210\u65f6\u95f4: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\")\n        f.write(\"=\" * 50 + \"\\n\\n\")\n\n        f.write(\"--- 1. \u9879\u76ee\u6982\u8ff0 ---\\n\")\n        f.write(\"\u672c\u9879\u76ee\u65e8\u5728\u901a\u8fc7\u5206\u6790\u7535\u5546\u4ea4\u6613\u6570\u636e\uff0c\u8fd0\u7528\u673a\u5668\u5b66\u4e60\u6280\u672f\u8bc6\u522b\u6f5c\u5728\u7684\u6b3a\u8bc8\u884c\u4e3a\uff0c\u4ee5\u4fdd\u62a4\u5e73\u53f0\u548c\u7528\u6237\u7684\u8d44\u91d1\u5b89\u5168\u3002\\n\")\n        f.write(\"\u91c7\u7528\u4e86\u65e0\u76d1\u7763\u5b66\u4e60\uff08\u5f02\u5e38\u68c0\u6d4b\uff09\u548c\u6709\u76d1\u7763\u5b66\u4e60\uff08\u5206\u7c7b\uff09\u4e24\u79cd\u65b9\u6cd5\u8fdb\u884c\u5bf9\u6bd4\u5206\u6790\u3002\\n\\n\")\n\n        f.write(\"--- 2. \u6570\u636e\u6982\u89c8 ---\\n\")\n        f.write(\"\u6570\u636e\u6765\u6e90: \u6a21\u62df\u751f\u6210\u7684\u7535\u5546\u5e73\u53f0\u4ea4\u6613\u6570\u636e\u3002\\n\")\n        f.write(\"\u6570\u636e\u89c4\u6a21: 10,000 \u7b14\u4ea4\u6613\uff0c\u5176\u4e2d 5% (500\u7b14) \u4e3a\u6b3a\u8bc8\u4ea4\u6613\u3002\\n\")\n        f.write(\"\u5173\u952e\u5b57\u6bb5: \u4ea4\u6613ID, \u7528\u6237ID, \u5546\u54c1ID, \u4ea4\u6613\u91d1\u989d, \u65f6\u95f4\u6233, \u7528\u6237\u5386\u53f2\u884c\u4e3a, \u8bbe\u5907\u4fe1\u606f, IP\u5730\u5740, \u5730\u7406\u4f4d\u7f6e\u7b49\u3002\\n\")\n        f.write(\"\u539f\u59cb\u6570\u636e\u5df2\u4fdd\u5b58\u4e3a CSV \u6587\u4ef6\u3002\\n\\n\")\n\n        f.write(\"--- 3. \u65e0\u76d1\u7763\u5f02\u5e38\u68c0\u6d4b ---\\n\")\n        f.write(\"\u76ee\u6807: \u5728\u6ca1\u6709\u6807\u7b7e\u7684\u60c5\u51b5\u4e0b\uff0c\u8bc6\u522b\u51fa\u4e0e\u5927\u591a\u6570\u6570\u636e\u663e\u8457\u4e0d\u540c\u7684\u5f02\u5e38\u70b9\u3002\\n\")\n        f.write(\"\u65b9\u6cd5: Isolation Forest, Local Outlier Factor (LOF)\u3002\\n\")\n        f.write(\"\u8bc4\u4f30: \u7531\u4e8e\u6ca1\u6709\u771f\u5b9e\u6807\u7b7e\uff0c\u8bc4\u4f30\u4e3b\u8981\u57fa\u4e8e\u6a21\u578b\u53d1\u73b0\u7684\u5f02\u5e38\u4e0e\u5df2\u77e5\u6b3a\u8bc8\u6837\u672c\u7684\u91cd\u5408\u5ea6\u3002\\n\\n\")\n        \n        f.write(\"\u5404\u6a21\u578b\u6027\u80fd\u5bf9\u6bd4:\\n\")\n        unsup_comparison_df = pd.DataFrame({\n            'Model': list(unsup_results.keys()),\n            'Accuracy': &#91;unsup_results&#91;k]&#91;'accuracy'] for k in unsup_results.keys()],\n            'Precision': &#91;unsup_results&#91;k]&#91;'precision'] for k in unsup_results.keys()],\n            'Recall': &#91;unsup_results&#91;k]&#91;'recall'] for k in unsup_results.keys()],\n            'F1-Score': &#91;unsup_results&#91;k]&#91;'f1'] for k in unsup_results.keys()],\n            'AUC-ROC': &#91;unsup_results&#91;k]&#91;'auc'] for k in unsup_results.keys()]\n        })\n        f.write(unsup_comparison_df.round(4).to_string(index=False))\n        f.write(\"\\n\\n\u6ce8\u610f\uff1a\u65e0\u76d1\u7763\u65b9\u6cd5\u7684\u7cbe\u786e\u7387\u548c\u53ec\u56de\u7387\u53ef\u80fd\u4e0d\u5982\u76d1\u7763\u65b9\u6cd5\uff0c\u4f46\u80fd\u53d1\u73b0\u672a\u77e5\u6a21\u5f0f\u3002\\n\\n\")\n\n        f.write(\"--- 4. \u6709\u76d1\u7763\u6b3a\u8bc8\u68c0\u6d4b ---\\n\")\n        f.write(\"\u76ee\u6807: \u5229\u7528\u5df2\u77e5\u7684\u6b3a\u8bc8\/\u6b63\u5e38\u6807\u7b7e\uff0c\u8bad\u7ec3\u5206\u7c7b\u6a21\u578b\u6765\u9884\u6d4b\u65b0\u4ea4\u6613\u662f\u5426\u4e3a\u6b3a\u8bc8\u3002\\n\")\n        f.write(\"\u65b9\u6cd5: Random Forest (\u4f7f\u7528\u4e86\u7c7b\u522b\u6743\u91cd\u5904\u7406\u6837\u672c\u4e0d\u5e73\u8861)\u3002\\n\")\n        f.write(\"\u8bc4\u4f30\u6307\u6807\u5305\u62ec: \u51c6\u786e\u7387 (Accuracy), \u7cbe\u786e\u7387 (Precision), \u53ec\u56de\u7387 (Recall), F1\u5206\u6570 (F1-Score), AUC-ROC\u3002\\n\\n\")\n        \n        f.write(f\"Random Forest \u6a21\u578b\u5728\u6d4b\u8bd5\u96c6\u4e0a\u7684\u8868\u73b0:\\n\")\n        f.write(f\"  - \u51c6\u786e\u7387 (Accuracy): {sup_metrics&#91;'accuracy']:.4f}\\n\")\n        f.write(f\"  - \u7cbe\u786e\u7387 (Precision): {sup_metrics&#91;'precision']:.4f}\\n\")\n        f.write(f\"  - \u53ec\u56de\u7387 (Recall): {sup_metrics&#91;'recall']:.4f}\\n\")\n        f.write(f\"  - F1\u5206\u6570 (F1-Score): {sup_metrics&#91;'f1']:.4f}\\n\")\n        f.write(f\"  - AUC-ROC: {sup_metrics&#91;'auc']:.4f}\\n\")\n        f.write(\"\u6df7\u6dc6\u77e9\u9635\u8be6\u7ec6\u5206\u6790\u4e86\u6a21\u578b\u7684\u9884\u6d4b\u7ed3\u679c\uff0c\u56fe\u8868\u5df2\u751f\u6210\u3002\\n\")\n        f.write(f\"\u6df7\u6dc6\u77e9\u9635\u56fe\u8868: {cm_path}\\n\\n\")\n\n        f.write(\"--- 5. \u5173\u952e\u9a71\u52a8\u56e0\u7d20\u5206\u6790 ---\\n\")\n        f.write(\"\u901a\u8fc7\u5206\u6790\u6700\u4f73\u6a21\u578b (Random Forest) \u7684\u7279\u5f81\u91cd\u8981\u6027\uff0c\u8bc6\u522b\u51fa\u533a\u5206\u6b3a\u8bc8\u548c\u6b63\u5e38\u4ea4\u6613\u7684\u6700\u5173\u952e\u56e0\u7d20\u3002\\n\")\n        f.write(\"\u7279\u5f81\u91cd\u8981\u6027\u6392\u5e8f (Top 10):\\n\")\n        f.write(feat_imp_df.head(10).to_string(index=False))\n        f.write(\"\\n\u4ece\u4e0a\u8868\u53ef\u4ee5\u770b\u51fa\uff0c\u54ea\u4e9b\u4ea4\u6613\u7279\u5f81\u6700\u80fd\u6307\u793a\u6b3a\u8bc8\u884c\u4e3a\u3002\\n\")\n        f.write(f\"\u7279\u5f81\u91cd\u8981\u6027\u56fe\u8868: {feat_imp_path}\\n\\n\")\n\n        f.write(\"--- 6. \u98ce\u9669\u7ba1\u7406\u4e0e\u4e1a\u52a1\u5e94\u7528\u5efa\u8bae ---\\n\")\n        f.write(\"1. \u5b9e\u65f6\u76d1\u63a7: \u5c06\u8bad\u7ec3\u597d\u7684\u6a21\u578b\u90e8\u7f72\u5230\u4ea4\u6613\u7cfb\u7edf\u4e2d\uff0c\u5bf9\u6bcf\u7b14\u5b9e\u65f6\u4ea4\u6613\u8fdb\u884c\u8bc4\u5206\u3002\\n\")\n        f.write(\"2. \u98ce\u9669\u9608\u503c: \u6839\u636e\u4e1a\u52a1\u53ef\u63a5\u53d7\u7684\u8bef\u62a5\u7387\uff0c\u8bbe\u5b9a\u6b3a\u8bc8\u6982\u7387\u9608\u503c\u3002\u8d85\u8fc7\u9608\u503c\u7684\u4ea4\u6613\u8fdb\u5165\u4eba\u5de5\u5ba1\u6838\u6216\u88ab\u6682\u65f6\u963b\u6b62\u3002\\n\")\n        f.write(\"3. \u591a\u5c42\u9632\u62a4:\\n\")\n        f.write(\"   - \u7ed3\u5408\u65e0\u76d1\u7763\u548c\u6709\u76d1\u7763\u6a21\u578b\u7684\u7ed3\u679c\uff0c\u63d0\u9ad8\u68c0\u6d4b\u7684\u9c81\u68d2\u6027\u3002\\n\")\n        f.write(\"   - \u5bf9\u4e8e\u9ad8\u98ce\u9669\u7279\u5f81\u7ec4\u5408\uff08\u5982'\u65b0\u8bbe\u5907'+'\u5927\u989d\u4ea4\u6613'+'\u975e\u5e38\u7528\u56fd\u5bb6'\uff09\uff0c\u5373\u4f7f\u6a21\u578b\u8bc4\u5206\u4e0d\u9ad8\u4e5f\u5e94\u52a0\u5f3a\u5173\u6ce8\u3002\\n\")\n        f.write(\"4. \u89c4\u5219\u5f15\u64ce: \u5bf9\u4e8e\u4e00\u4e9b\u660e\u663e\u7684\u6b3a\u8bc8\u6a21\u5f0f\uff08\u5982IP\u5730\u5740\u9ed1\u540d\u5355\uff09\uff0c\u53ef\u4ee5\u4f7f\u7528\u89c4\u5219\u5f15\u64ce\u5feb\u901f\u62e6\u622a\u3002\\n\")\n        f.write(\"5. \u6a21\u578b\u8fed\u4ee3: \u5b9a\u671f\u4f7f\u7528\u6700\u65b0\u7684\u5e26\u6807\u7b7e\u6570\u636e\u91cd\u65b0\u8bad\u7ec3\u6a21\u578b\uff0c\u4ee5\u9002\u5e94\u4e0d\u65ad\u53d8\u5316\u7684\u6b3a\u8bc8\u624b\u6bb5\u3002\\n\")\n        f.write(\"6. \u7528\u6237\u6559\u80b2: \u63d0\u9192\u7528\u6237\u4fdd\u62a4\u8d26\u6237\u5b89\u5168\uff0c\u5982\u4e0d\u6cc4\u9732\u5bc6\u7801\u3001\u4e0d\u70b9\u51fb\u53ef\u7591\u94fe\u63a5\u7b49\u3002\\n\\n\")\n\n        f.write(\"=\" * 50 + \"\\n\")\n        f.write(\"                    \u62a5\u544a\u7ed3\u675f\\n\")\n        f.write(\"=\" * 50 + \"\\n\")\n\n    print(f\"\u6b3a\u8bc8\u68c0\u6d4b\u5206\u6790\u62a5\u544a\u5df2\u751f\u6210: {report_filename}\")\n\n# --- \u4e3b\u51fd\u6570 ---\n\ndef main():\n    \"\"\"\u4e3b\u51fd\u6570\"\"\"\n    # 1. \u751f\u6210\u6570\u636e\n    df_fraud = generate_sample_fraud_data(NUM_TRANSACTIONS, FRAUD_RATIO)\n    \n    # 2. \u6570\u636e\u9884\u5904\u7406\n    X, y, le_country, feature_cols = preprocess_data(df_fraud)\n    \n    # 3. \u65e0\u76d1\u7763\u5f02\u5e38\u68c0\u6d4b\n    unsup_results = perform_unsupervised_detection(X, y)\n    \n    # 4. \u6709\u76d1\u7763\u6b3a\u8bc8\u68c0\u6d4b\n    sup_results, cm_path = perform_supervised_detection(X, y)\n    \n    # 5. \u7279\u5f81\u91cd\u8981\u6027\u5206\u6790 (\u9488\u5bf9\u6709\u76d1\u7763\u6a21\u578b)\n    best_model = sup_results&#91;'Random Forest']&#91;'model']\n    feat_imp_df, feat_imp_path = analyze_feature_importance(best_model, feature_cols, 'Random Forest')\n    \n    # 6. \u751f\u6210\u62a5\u544a\n    generate_fraud_detection_report(unsup_results, sup_results, cm_path, feat_imp_df, feat_imp_path)\n    \n    print(\"\\n\u7528\u6237\u98ce\u9669\u7ba1\u7406\u548c\u6b3a\u8bc8\u884c\u4e3a\u68c0\u6d4b\u5206\u6790\u6d41\u7a0b\u5b8c\u6210\u3002\")\n\nif __name__ == \"__main__\":\n    main()<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u8be5\u811a\u672c\u5c06\u5305\u542b\u4ee5\u4e0b\u529f\u80fd\uff1a\u4f7f\u7528\u968f\u673a\u68ee\u6797\uff08Random Forest\uff09\u8fdb\u884c\u6709\u76d1\u7763\u7684\u6b3a\u8bc8\u68c0\u6d4b<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[28],"views":351,"_links":{"self":[{"href":"http:\/\/viplao.com\/index.php\/wp-json\/wp\/v2\/posts\/3897"}],"collection":[{"href":"http:\/\/viplao.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/viplao.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/viplao.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/viplao.com\/index.php\/wp-json\/wp\/v2\/comments?post=3897"}],"version-history":[{"count":2,"href":"http:\/\/viplao.com\/index.php\/wp-json\/wp\/v2\/posts\/3897\/revisions"}],"predecessor-version":[{"id":3913,"href":"http:\/\/viplao.com\/index.php\/wp-json\/wp\/v2\/posts\/3897\/revisions\/3913"}],"wp:attachment":[{"href":"http:\/\/viplao.com\/index.php\/wp-json\/wp\/v2\/media?parent=3897"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/viplao.com\/index.php\/wp-json\/wp\/v2\/categories?post=3897"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/viplao.com\/index.php\/wp-json\/wp\/v2\/tags?post=3897"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}