[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M781RJ4B4N1RHWRC2YPG75J3":3,"skill-same:01M781RJ4B4N1RHWRC2YPG75J3":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M781RJ4B4N1RHWRC2YPG75J3","Anomaly Detection",null,"Identify unusual patterns, outliers, and anomalies in data using statistical methods, isolation forests, and autoencoders for fraud detection and quality monitoring","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fskills_sh\u002Fs\u002Fskills-sh_aj-geddes_useful-ai-prompts_anomaly-detection\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: Anomaly Detection\ndescription: Identify unusual patterns, outliers, and anomalies in data using statistical methods, isolation forests, and autoencoders for fraud detection and quality monitoring\n---\n\n# Anomaly Detection\n\n## Overview\n\nAnomaly detection identifies unusual patterns, outliers, and anomalies in data that deviate significantly from normal behavior, enabling fraud detection and system monitoring.\n\n## When to Use\n\n- Detecting fraudulent transactions or suspicious activity in financial data\n- Identifying system failures, network intrusions, or security breaches\n- Monitoring manufacturing quality and identifying defective products\n- Finding unusual patterns in healthcare data or patient vital signs\n- Detecting abnormal sensor readings in IoT or industrial systems\n- Identifying outliers in customer behavior for targeted intervention\n\n## Detection Methods\n\n- **Statistical**: Z-score, IQR, modified Z-score\n- **Distance-based**: K-nearest neighbors, Local Outlier Factor\n- **Isolation**: Isolation Forest\n- **Density-based**: DBSCAN\n- **Deep Learning**: Autoencoders, GANs\n\n## Anomaly Types\n\n- **Point Anomalies**: Single unusual records\n- **Contextual**: Unusual in specific context\n- **Collective**: Unusual patterns in sequences\n- **Novel Classes**: Completely new patterns\n\n## Implementation with Python\n\n```python\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.neighbors import LocalOutlierFactor\nfrom sklearn.covariance import EllipticEnvelope\nfrom scipy import stats\n\n# Generate sample data with anomalies\nnp.random.seed(42)\n\n# Normal data\nn_normal = 950\nnormal_data = np.random.normal(100, 15, (n_normal, 2))\n\n# Anomalies\nn_anomalies = 50\nanomalies = np.random.uniform(0, 200, (n_anomalies, 2))\nanomalies[n_anomalies\u002F\u002F2:, 0] = np.random.uniform(80, 120, n_anomalies\u002F\u002F2)\nanomalies[n_anomalies\u002F\u002F2:, 1] = np.random.uniform(-50, 0, n_anomalies\u002F\u002F2)\n\nX = np.vstack([normal_data, anomalies])\ny_true = np.hstack([np.zeros(n_normal), np.ones(n_anomalies)])\n\ndf = pd.DataFrame(X, columns=['Feature1', 'Feature2'])\ndf['is_anomaly_true'] = y_true\n\nprint(\"Data Summary:\")\nprint(f\"Normal samples: {n_normal}\")\nprint(f\"Anomalies: {n_anomalies}\")\nprint(f\"Total: {len(df)}\")\n\n# Standardize\nscaler = StandardScaler()\nX_scaled = scaler.fit_transform(X)\n\n# 1. Statistical Methods (Z-score)\nz_scores = np.abs(stats.zscore(X))\nz_anomaly_mask = (z_scores > 3).any(axis=1)\ndf['z_score_anomaly'] = z_anomaly_mask\n\nprint(f\"\\n1. Z-score Method:\")\nprint(f\"Anomalies detected: {z_anomaly_mask.sum()}\")\nprint(f\"Accuracy: {(z_anomaly_mask == y_true).mean():.2%}\")\n\n# 2. Isolation Forest\niso_forest = IsolationForest(contamination=n_anomalies\u002Flen(df), random_state=42)\niso_predictions = iso_forest.fit_predict(X_scaled)\niso_anomaly_mask = iso_predictions == -1\niso_scores = iso_forest.score_samples(X_scaled)\n\ndf['iso_anomaly'] = iso_anomaly_mask\ndf['iso_score'] = iso_scores\n\nprint(f\"\\n2. Isolation Forest:\")\nprint(f\"Anomalies detected: {iso_anomaly_mask.sum()}\")\nprint(f\"Accuracy: {(iso_anomaly_mask == y_true).mean():.2%}\")\n\n# 3. Local Outlier Factor\nlof = LocalOutlierFactor(n_neighbors=20, contamination=n_anomalies\u002Flen(df))\nlof_predictions = lof.fit_predict(X_scaled)\nlof_anomaly_mask = lof_predictions == -1\nlof_scores = lof.negative_outlier_factor_\n\ndf['lof_anomaly'] = lof_anomaly_mask\ndf['lof_score'] = lof_scores\n\nprint(f\"\\n3. Local Outlier Factor:\")\nprint(f\"Anomalies detected: {lof_anomaly_mask.sum()}\")\nprint(f\"Accuracy: {(lof_anomaly_mask == y_true).mean():.2%}\")\n\n# 4. Elliptic Envelope (Robust Covariance)\nee = EllipticEnvelope(contamination=n_anomalies\u002Flen(df), random_state=42)\nee_predictions = ee.fit_predict(X_scaled)\nee_anomaly_mask = ee_predictions == -1\nee_scores = ee.mahalanobis(X_scaled)\n\ndf['ee_anomaly'] = ee_anomaly_mask\ndf['ee_score'] = ee_scores\n\nprint(f\"\\n4. Elliptic Envelope:\")\nprint(f\"Anomalies detected: {ee_anomaly_mask.sum()}\")\nprint(f\"Accuracy: {(ee_anomaly_mask == y_true).mean():.2%}\")\n\n# 5. IQR Method\nQ1 = np.percentile(X, 25, axis=0)\nQ3 = np.percentile(X, 75, axis=0)\nIQR = Q3 - Q1\nlower_bound = Q1 - 1.5 * IQR\nupper_bound = Q3 + 1.5 * IQR\n\niqr_anomaly_mask = ((X \u003C lower_bound) | (X > upper_bound)).any(axis=1)\ndf['iqr_anomaly'] = iqr_anomaly_mask\n\nprint(f\"\\n5. IQR Method:\")\nprint(f\"Anomalies detected: {iqr_anomaly_mask.sum()}\")\nprint(f\"Accuracy: {(iqr_anomaly_mask == y_true).mean():.2%}\")\n\n# Visualization of anomaly detection methods\nfig, axes = plt.subplots(2, 3, figsize=(15, 10))\n\nmethods = [\n    (z_anomaly_mask, 'Z-score', None),\n    (iso_anomaly_mask, 'Isolation Forest', iso_scores),\n    (lof_anomaly_mask, 'LOF', lof_scores),\n    (ee_anomaly_mask, 'Elliptic Envelope', ee_scores),\n    (iqr_anomaly_mask, 'IQR', None),\n]\n\n# True anomalies\nax = axes[0, 0]\ncolors = ['blue' if not a else 'red' for a in y_true]\nax.scatter(df['Feature1'], df['Feature2'], c=colors, alpha=0.6, s=30)\nax.set_title('True Anomalies')\nax.set_xlabel('Feature 1')\nax.set_ylabel('Feature 2')\n\n# Plot each method\nfor idx, (anomaly_mask, method_name, scores) in enumerate(methods):\n    ax = axes.flatten()[idx + 1]\n\n    if scores is not None:\n        scatter = ax.scatter(df['Feature1'], df['Feature2'], c=scores, cmap='RdYlBu_r', alpha=0.6, s=30)\n        plt.colorbar(scatter, ax=ax, label='Score')\n    else:\n        colors = ['red' if a else 'blue' for a in anomaly_mask]\n        ax.scatter(df['Feature1'], df['Feature2'], c=colors, alpha=0.6, s=30)\n\n    ax.set_title(f'{method_name}\\n({anomaly_mask.sum()} anomalies)')\n    ax.set_xlabel('Feature 1')\n    ax.set_ylabel('Feature 2')\n\nplt.tight_layout()\nplt.show()\n\n# 6. Anomaly score comparison\nfig, axes = plt.subplots(2, 2, figsize=(14, 8))\n\n# ISO Forest scores\naxes[0, 0].hist(iso_scores[~y_true], bins=30, alpha=0.7, label='Normal', color='blue')\naxes[0, 0].hist(iso_scores[y_true == 1], bins=10, alpha=0.7, label='Anomaly', color='red')\naxes[0, 0].set_xlabel('Anomaly Score')\naxes[0, 0].set_title('Isolation Forest Score Distribution')\naxes[0, 0].legend()\naxes[0, 0].grid(True, alpha=0.3)\n\n# LOF scores\naxes[0, 1].hist(lof_scores[~y_true], bins=30, alpha=0.7, label='Normal', color='blue')\naxes[0, 1].hist(lof_scores[y_true == 1], bins=10, alpha=0.7, label='Anomaly', color='red')\naxes[0, 1].set_xlabel('Anomaly Score')\naxes[0, 1].set_title('LOF Score Distribution')\naxes[0, 1].legend()\naxes[0, 1].grid(True, alpha=0.3)\n\n# ROC-like curve for Isolation Forest\niso_scores_sorted = np.sort(iso_scores)\ndetected_at_threshold = []\nfor threshold in iso_scores_sorted:\n    detected = (iso_scores \u003C= threshold).sum()\n    true_detected = ((iso_scores \u003C= threshold) & (y_true == 1)).sum()\n    if detected > 0:\n        precision = true_detected \u002F detected\n        recall = true_detected \u002F n_anomalies\n        detected_at_threshold.append({'Threshold': threshold, 'Precision': precision, 'Recall': recall})\n\nif detected_at_threshold:\n    threshold_df = pd.DataFrame(detected_at_threshold)\n    axes[1, 0].plot(threshold_df['Recall'], threshold_df['Precision'], linewidth=2)\n    axes[1, 0].set_xlabel('Recall')\n    axes[1, 0].set_ylabel('Precision')\n    axes[1, 0].set_title('Precision-Recall Curve (Isolation Forest)')\n    axes[1, 0].grid(True, alpha=0.3)\n\n# Method comparison\nmethods_comparison = pd.DataFrame({\n    'Method': ['Z-score', 'Isolation Forest', 'LOF', 'Elliptic Envelope', 'IQR'],\n    'Accuracy': [\n        (z_anomaly_mask == y_true).mean(),\n        (iso_anomaly_mask == y_true).mean(),\n        (lof_anomaly_mask == y_true).mean(),\n        (ee_anomaly_mask == y_true).mean(),\n        (iqr_anomaly_mask == y_true).mean(),\n    ]\n})\n\naxes[1, 1].barh(methods_comparison['Method'], methods_comparison['Accuracy'], color='steelblue', edgecolor='black')\naxes[1, 1].set_xlabel('Accuracy')\naxes[1, 1].set_title('Method Comparison')\naxes[1, 1].set_xlim([0, 1])\nfor i, v in enumerate(methods_comparison['Accuracy']):\n    axes[1, 1].text(v, i, f' {v:.2%}', va='center')\n\nplt.tight_layout()\nplt.show()\n\n# 7. Ensemble anomaly detection\n# Combine multiple methods\nensemble_votes = (z_anomaly_mask.astype(int) +\n                  iso_anomaly_mask.astype(int) +\n                  lof_anomaly_mask.astype(int) +\n                  ee_anomaly_mask.astype(int) +\n                  iqr_anomaly_mask.astype(int))\n\ndf['ensemble_votes'] = ensemble_votes\nensemble_anomaly = ensemble_votes >= 3  # Majority vote\n\nprint(f\"\\n6. Ensemble (Majority Vote):\")\nprint(f\"Anomalies detected: {ensemble_anomaly.sum()}\")\nprint(f\"Accuracy: {(ensemble_anomaly == y_true).mean():.2%}\")\n\n# Visualize ensemble\nfig, ax = plt.subplots(figsize=(10, 8))\nscatter = ax.scatter(df['Feature1'], df['Feature2'], c=ensemble_votes, cmap='RdYlGn_r',\n                     s=100 * (ensemble_anomaly.astype(int) + 0.5), alpha=0.6, edgecolors='black')\nax.set_xlabel('Feature 1')\nax.set_ylabel('Feature 2')\nax.set_title('Ensemble Anomaly Detection (Color: Vote Count, Size: Anomaly)')\ncbar = plt.colorbar(scatter, ax=ax, label='Number of Methods')\nplt.show()\n\n# 8. Time-series anomalies\ntime_series_data = np.sin(np.arange(100) * 0.2) * 10 + 100\ntime_series_data = time_series_data + np.random.normal(0, 2, 100)\n# Add anomalies\ntime_series_data[25] = 150\ntime_series_data[50] = 50\ntime_series_data[75] = 140\n\n# Detect using rolling statistics\nrolling_mean = pd.Series(time_series_data).rolling(window=5).mean()\nrolling_std = pd.Series(time_series_data).rolling(window=5).std()\nz_scores_ts = np.abs((time_series_data - rolling_mean) \u002F rolling_std) > 2\n\nfig, ax = plt.subplots(figsize=(12, 5))\nax.plot(time_series_data, linewidth=1, label='Data')\nax.plot(rolling_mean, linewidth=2, label='Rolling Mean')\nax.scatter(np.where(z_scores_ts)[0], time_series_data[z_scores_ts], color='red', s=100, label='Anomalies', zorder=5)\nax.fill_between(range(len(time_series_data)), rolling_mean - 2*rolling_std, rolling_mean + 2*rolling_std,\n                alpha=0.2, label='±2 Std Dev')\nax.set_xlabel('Time')\nax.set_ylabel('Value')\nax.set_title('Time-Series Anomaly Detection')\nax.legend()\nax.grid(True, alpha=0.3)\nplt.tight_layout()\nplt.show()\n\nprint(\"\\nAnomaly detection analysis complete!\")\n```\n\n## Method Selection Guide\n\n- **Z-score**: Simple, fast, assumes normal distribution\n- **IQR**: Robust, non-parametric, good for outliers\n- **Isolation Forest**: Efficient, good for high dimensions\n- **LOF**: Density-based, finds local anomalies\n- **Autoencoders**: Complex patterns, deep learning\n\n## Threshold Selection\n\n- **Conservative**: Fewer false positives, more false negatives\n- **Aggressive**: More anomalies flagged, more false positives\n- **Data-driven**: Use validation set to optimize threshold\n\n## Deliverables\n\n- Anomaly detection results\n- Anomaly scores visualization\n- Comparison of methods\n- Identified anomalous records\n- Recommendation for production deployment\n- Threshold optimization analysis\n","# Anomaly Detection\n\n## Overview\n\nAnomaly detection identifies unusual patterns, outliers, and anomalies in data that deviate significantly from normal behavior, enabling fraud detection and system monitoring.\n\n## When to Use\n\n- Detecting fraudulent transactions or suspicious activity in financial data\n- Identifying system failures, network intrusions, or security breaches\n- Monitoring manufacturing quality and identifying defective products\n- Finding unusual patterns in healthcare data or patient vital signs\n- Detecting abnormal sensor readings in IoT or industrial systems\n- Identifying outliers in customer behavior for targeted intervention\n\n## Detection Methods\n\n- **Statistical**: Z-score, IQR, modified Z-score\n- **Distance-based**: K-nearest neighbors, Local Outlier Factor\n- **Isolation**: Isolation Forest\n- **Density-based**: DBSCAN\n- **Deep Learning**: Autoencoders, GANs\n\n## Anomaly Types\n\n- **Point Anomalies**: Single unusual records\n- **Contextual**: Unusual in specific context\n- **Collective**: Unusual patterns in sequences\n- **Novel Classes**: Completely new patterns\n\n## Implementation with Python\n\n```python\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.neighbors import LocalOutlierFactor\nfrom sklearn.covariance import EllipticEnvelope\nfrom scipy import stats\n\n# Generate sample data with anomalies\nnp.random.seed(42)\n\n# Normal data\nn_normal = 950\nnormal_data = np.random.normal(100, 15, (n_normal, 2))\n\n# Anomalies\nn_anomalies = 50\nanomalies = np.random.uniform(0, 200, (n_anomalies, 2))\nanomalies[n_anomalies\u002F\u002F2:, 0] = np.random.uniform(80, 120, n_anomalies\u002F\u002F2)\nanomalies[n_anomalies\u002F\u002F2:, 1] = np.random.uniform(-50, 0, n_anomalies\u002F\u002F2)\n\nX = np.vstack([normal_data, anomalies])\ny_true = np.hstack([np.zeros(n_normal), np.ones(n_anomalies)])\n\ndf = pd.DataFrame(X, columns=['Feature1', 'Feature2'])\ndf['is_anomaly_true'] = y_true\n\nprint(\"Data Summary:\")\nprint(f\"Normal samples: {n_normal}\")\nprint(f\"Anomalies: {n_anomalies}\")\nprint(f\"Total: {len(df)}\")\n\n# Standardize\nscaler = StandardScaler()\nX_scaled = scaler.fit_transform(X)\n\n# 1. Statistical Methods (Z-score)\nz_scores = np.abs(stats.zscore(X))\nz_anomaly_mask = (z_scores > 3).any(axis=1)\ndf['z_score_anomaly'] = z_anomaly_mask\n\nprint(f\"\\n1. Z-score Method:\")\nprint(f\"Anomalies detected: {z_anomaly_mask.sum()}\")\nprint(f\"Accuracy: {(z_anomaly_mask == y_true).mean():.2%}\")\n\n# 2. Isolation Forest\niso_forest = IsolationForest(contamination=n_anomalies\u002Flen(df), random_state=42)\niso_predictions = iso_forest.fit_predict(X_scaled)\niso_anomaly_mask = iso_predictions == -1\niso_scores = iso_forest.score_samples(X_scaled)\n\ndf['iso_anomaly'] = iso_anomaly_mask\ndf['iso_score'] = iso_scores\n\nprint(f\"\\n2. Isolation Forest:\")\nprint(f\"Anomalies detected: {iso_anomaly_mask.sum()}\")\nprint(f\"Accuracy: {(iso_anomaly_mask == y_true).mean():.2%}\")\n\n# 3. Local Outlier Factor\nlof = LocalOutlierFactor(n_neighbors=20, contamination=n_anomalies\u002Flen(df))\nlof_predictions = lof.fit_predict(X_scaled)\nlof_anomaly_mask = lof_predictions == -1\nlof_scores = lof.negative_outlier_factor_\n\ndf['lof_anomaly'] = lof_anomaly_mask\ndf['lof_score'] = lof_scores\n\nprint(f\"\\n3. Local Outlier Factor:\")\nprint(f\"Anomalies detected: {lof_anomaly_mask.sum()}\")\nprint(f\"Accuracy: {(lof_anomaly_mask == y_true).mean():.2%}\")\n\n# 4. Elliptic Envelope (Robust Covariance)\nee = EllipticEnvelope(contamination=n_anomalies\u002Flen(df), random_state=42)\nee_predictions = ee.fit_predict(X_scaled)\nee_anomaly_mask = ee_predictions == -1\nee_scores = ee.mahalanobis(X_scaled)\n\ndf['ee_anomaly'] = ee_anomaly_mask\ndf['ee_score'] = ee_scores\n\nprint(f\"\\n4. Elliptic Envelope:\")\nprint(f\"Anomalies detected: {ee_anomaly_mask.sum()}\")\nprint(f\"Accuracy: {(ee_anomaly_mask == y_true).mean():.2%}\")\n\n# 5. IQR Method\nQ1 = np.percentile(X, 25, axis=0)\nQ3 = np.percentile(X, 75, axis=0)\nIQR = Q3 - Q1\nlower_bound = Q1 - 1.5 * IQR\nupper_bound = Q3 + 1.5 * IQR\n\niqr_anomaly_mask = ((X \u003C lower_bound) | (X > upper_bound)).any(axis=1)\ndf['iqr_anomaly'] = iqr_anomaly_mask\n\nprint(f\"\\n5. IQR Method:\")\nprint(f\"Anomalies detected: {iqr_anomaly_mask.sum()}\")\nprint(f\"Accuracy: {(iqr_anomaly_mask == y_true).mean():.2%}\")\n\n# Visualization of anomaly detection methods\nfig, axes = plt.subplots(2, 3, figsize=(15, 10))\n\nmethods = [\n    (z_anomaly_mask, 'Z-score', None),\n    (iso_anomaly_mask, 'Isolation Forest', iso_scores),\n    (lof_anomaly_mask, 'LOF', lof_scores),\n    (ee_anomaly_mask, 'Elliptic Envelope', ee_scores),\n    (iqr_anomaly_mask, 'IQR', None),\n]\n\n# True anomalies\nax = axes[0, 0]\ncolors = ['blue' if not a else 'red' for a in y_true]\nax.scatter(df['Feature1'], df['Feature2'], c=colors, alpha=0.6, s=30)\nax.set_title('True Anomalies')\nax.set_xlabel('Feature 1')\nax.set_ylabel('Feature 2')\n\n# Plot each method\nfor idx, (anomaly_mask, method_name, scores) in enumerate(methods):\n    ax = axes.flatten()[idx + 1]\n\n    if scores is not None:\n        scatter = ax.scatter(df['Feature1'], df['Feature2'], c=scores, cmap='RdYlBu_r', alpha=0.6, s=30)\n        plt.colorbar(scatter, ax=ax, label='Score')\n    else:\n        colors = ['red' if a else 'blue' for a in anomaly_mask]\n        ax.scatter(df['Feature1'], df['Feature2'], c=colors, alpha=0.6, s=30)\n\n    ax.set_title(f'{method_name}\\n({anomaly_mask.sum()} anomalies)')\n    ax.set_xlabel('Feature 1')\n    ax.set_ylabel('Feature 2')\n\nplt.tight_layout()\nplt.show()\n\n# 6. Anomaly score comparison\nfig, axes = plt.subplots(2, 2, figsize=(14, 8))\n\n# ISO Forest scores\naxes[0, 0].hist(iso_scores[~y_true], bins=30, alpha=0.7, label='Normal', color='blue')\naxes[0, 0].hist(iso_scores[y_true == 1], bins=10, alpha=0.7, label='Anomaly', color='red')\naxes[0, 0].set_xlabel('Anomaly Score')\naxes[0, 0].set_title('Isolation Forest Score Distribution')\naxes[0, 0].legend()\naxes[0, 0].grid(True, alpha=0.3)\n\n# LOF scores\naxes[0, 1].hist(lof_scores[~y_true], bins=30, alpha=0.7, label='Normal', color='blue')\naxes[0, 1].hist(lof_scores[y_true == 1], bins=10, alpha=0.7, label='Anomaly', color='red')\naxes[0, 1].set_xlabel('Anomaly Score')\naxes[0, 1].set_title('LOF Score Distribution')\naxes[0, 1].legend()\naxes[0, 1].grid(True, alpha=0.3)\n\n# ROC-like curve for Isolation Forest\niso_scores_sorted = np.sort(iso_scores)\ndetected_at_threshold = []\nfor threshold in iso_scores_sorted:\n    detected = (iso_scores \u003C= threshold).sum()\n    true_detected = ((iso_scores \u003C= threshold) & (y_true == 1)).sum()\n    if detected > 0:\n        precision = true_detected \u002F detected\n        recall = true_detected \u002F n_anomalies\n        detected_at_threshold.append({'Threshold': threshold, 'Precision': precision, 'Recall': recall})\n\nif detected_at_threshold:\n    threshold_df = pd.DataFrame(detected_at_threshold)\n    axes[1, 0].plot(threshold_df['Recall'], threshold_df['Precision'], linewidth=2)\n    axes[1, 0].set_xlabel('Recall')\n    axes[1, 0].set_ylabel('Precision')\n    axes[1, 0].set_title('Precision-Recall Curve (Isolation Forest)')\n    axes[1, 0].grid(True, alpha=0.3)\n\n# Method comparison\nmethods_comparison = pd.DataFrame({\n    'Method': ['Z-score', 'Isolation Forest', 'LOF', 'Elliptic Envelope', 'IQR'],\n    'Accuracy': [\n        (z_anomaly_mask == y_true).mean(),\n        (iso_anomaly_mask == y_true).mean(),\n        (lof_anomaly_mask == y_true).mean(),\n        (ee_anomaly_mask == y_true).mean(),\n        (iqr_anomaly_mask == y_true).mean(),\n    ]\n})\n\naxes[1, 1].barh(methods_comparison['Method'], methods_comparison['Accuracy'], color='steelblue', edgecolor='black')\naxes[1, 1].set_xlabel('Accuracy')\naxes[1, 1].set_title('Method Comparison')\naxes[1, 1].set_xlim([0, 1])\nfor i, v in enumerate(methods_comparison['Accuracy']):\n    axes[1, 1].text(v, i, f' {v:.2%}', va='center')\n\nplt.tight_layout()\nplt.show()\n\n# 7. Ensemble anomaly detection\n# Combine multiple methods\nensemble_votes = (z_anomaly_mask.astype(int) +\n                  iso_anomaly_mask.astype(int) +\n                  lof_anomaly_mask.astype(int) +\n                  ee_anomaly_mask.astype(int) +\n                  iqr_anomaly_mask.astype(int))\n\ndf['ensemble_votes'] = ensemble_votes\nensemble_anomaly = ensemble_votes >= 3  # Majority vote\n\nprint(f\"\\n6. Ensemble (Majority Vote):\")\nprint(f\"Anomalies detected: {ensemble_anomaly.sum()}\")\nprint(f\"Accuracy: {(ensemble_anomaly == y_true).mean():.2%}\")\n\n# Visualize ensemble\nfig, ax = plt.subplots(figsize=(10, 8))\nscatter = ax.scatter(df['Feature1'], df['Feature2'], c=ensemble_votes, cmap='RdYlGn_r',\n                     s=100 * (ensemble_anomaly.astype(int) + 0.5), alpha=0.6, edgecolors='black')\nax.set_xlabel('Feature 1')\nax.set_ylabel('Feature 2')\nax.set_title('Ensemble Anomaly Detection (Color: Vote Count, Size: Anomaly)')\ncbar = plt.colorbar(scatter, ax=ax, label='Number of Methods')\nplt.show()\n\n# 8. Time-series anomalies\ntime_series_data = np.sin(np.arange(100) * 0.2) * 10 + 100\ntime_series_data = time_series_data + np.random.normal(0, 2, 100)\n# Add anomalies\ntime_series_data[25] = 150\ntime_series_data[50] = 50\ntime_series_data[75] = 140\n\n# Detect using rolling statistics\nrolling_mean = pd.Series(time_series_data).rolling(window=5).mean()\nrolling_std = pd.Series(time_series_data).rolling(window=5).std()\nz_scores_ts = np.abs((time_series_data - rolling_mean) \u002F rolling_std) > 2\n\nfig, ax = plt.subplots(figsize=(12, 5))\nax.plot(time_series_data, linewidth=1, label='Data')\nax.plot(rolling_mean, linewidth=2, label='Rolling Mean')\nax.scatter(np.where(z_scores_ts)[0], time_series_data[z_scores_ts], color='red', s=100, label='Anomalies', zorder=5)\nax.fill_between(range(len(time_series_data)), rolling_mean - 2*rolling_std, rolling_mean + 2*rolling_std,\n                alpha=0.2, label='±2 Std Dev')\nax.set_xlabel('Time')\nax.set_ylabel('Value')\nax.set_title('Time-Series Anomaly Detection')\nax.legend()\nax.grid(True, alpha=0.3)\nplt.tight_layout()\nplt.show()\n\nprint(\"\\nAnomaly detection analysis complete!\")\n```\n\n## Method Selection Guide\n\n- **Z-score**: Simple, fast, assumes normal distribution\n- **IQR**: Robust, non-parametric, good for outliers\n- **Isolation Forest**: Efficient, good for high dimensions\n- **LOF**: Density-based, finds local anomalies\n- **Autoencoders**: Complex patterns, deep learning\n\n## Threshold Selection\n\n- **Conservative**: Fewer false positives, more false negatives\n- **Aggressive**: More anomalies flagged, more false positives\n- **Data-driven**: Use validation set to optimize threshold\n\n## Deliverables\n\n- Anomaly detection results\n- Anomaly scores visualization\n- Comparison of methods\n- Identified anomalous records\n- Recommendation for production deployment\n- Threshold optimization analysis\n",{"name":5,"description":7},"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fskills_sh\u002Fs\u002Fskills-sh_aj-geddes_useful-ai-prompts_anomaly-detection",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Anomaly Detection\"",{"tool":39,"command":40},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Anomaly Detection\"",{"tool":42,"command":43},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Anomaly Detection\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fskills_sh\u002Fs\u002Fskills-sh_aj-geddes_useful-ai-prompts_anomaly-detection\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]