isEqual - return 1 if x == y, and 0 otherwise & negate - return -x

本文介绍如何使用位操作符实现整数的比较及取反功能,通过简单的位操作达到高效运算的目的,并提供具体的代码示例。

 

/*
 * isEqual - return 1 if x == y, and 0 otherwise
 *   Examples: isEqual(5,5) = 1, isEqual(4,5) = 0
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 5
 *   Rating: 2
 */
int isEqual(int x, int y) {
    /*return 1 if x == y, and 0 otherwise*/
    
  return !(x^y);

}

 

/*
 * negate - return -x
 *   Example: negate(1) = -1.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 5
 *   Rating: 2
 */
int negate(int x) {
    /*negate - return -x*/
    x = ~x;
    x +=1;
  return x;

}

&quot;&quot;&quot; Outlier Detection Toolbox ========================= This is a single-file distribution (for ease of preview) of a production-grade outlier/anomaly detection toolbox intended to be split into a small package: outlier_detection/ ├── __init__.py ├── utils.py ├── statistical.py ├── distance_density.py ├── model_based.py ├── deep_learning.py ├── ensemble.py ├── visualization.py └── cli.py --- NOTE --- This code block contains *all* modules concatenated (with file headers) so you can preview and copy each file out into separate .py files. When you save them as separate files the package will work as expected. Design goals (what you asked for): - Detailed, well-documented functions (purpose, math, applicability, edge-cases) - Robust handling of NaNs, constant columns, categorical data - Functions return structured metadata + masks + scores so you can inspect - Utilities for ensemble combining methods and producing a readable report - Optional deep learning methods (AutoEncoder/VAE) with clear dependency instructions and graceful error messages if libraries are missing. Dependencies (recommended): pip install numpy pandas scipy scikit-learn matplotlib joblib tensorflow&gt;=2.0 If you prefer PyTorch for deep models you can adapt deep_learning.py accordingly. &quot;&quot;&quot; # --------------------------- # File: outlier_detection/__init__.py # --------------------------- __version__ = &quot;0.1.0&quot; # make it easy to import core helpers from typing import Dict from .utils import ensure_dataframe, OutlierResult, summarize_results, recommend_methods from .statistical import z_score_method, modified_z_score, iqr_method, grubbs_test from .distance_density import lof_method, mahalanobis_method, dbscan_method, knn_distance_method from .model_based import ( isolation_forest_method, one_class_svm_method, pca_reconstruction_error, gmm_method, elliptic_envelope_method, ) # deep_learning module is optional (heavy dependency) try: from .deep_learning import autoencoder_method, vae_method except Exception: # graceful: user may not have TF installed; import will raise at use time autoencoder_method = None vae_method = None from .ensemble import ensemble_methods, aggregate_scores from .visualization import plot_boxplot, plot_pair_scatter __all__ = [ &quot;__version__&quot;, &quot;ensure_dataframe&quot;, &quot;OutlierResult&quot;, &quot;summarize_results&quot;, &quot;recommend_methods&quot;, &quot;z_score_method&quot;, &quot;modified_z_score&quot;, &quot;iqr_method&quot;, &quot;grubbs_test&quot;, &quot;lof_method&quot;, &quot;mahalanobis_method&quot;, &quot;dbscan_method&quot;, &quot;knn_distance_method&quot;, &quot;isolation_forest_method&quot;, &quot;one_class_svm_method&quot;, &quot;pca_reconstruction_error&quot;, &quot;gmm_method&quot;, &quot;elliptic_envelope_method&quot;, &quot;autoencoder_method&quot;, &quot;vae_method&quot;, &quot;ensemble_methods&quot;, &quot;aggregate_scores&quot;, &quot;plot_boxplot&quot;, &quot;plot_pair_scatter&quot;, ] # --------------------------- # File: outlier_detection/utils.py # --------------------------- &quot;&quot;&quot; Utilities for the outlier detection package. Key responsibilities: - Input validation and type normalization - Handling numeric / categorical separation - Standardization and robust scaling helpers - A consistent result object shape used by all detectors &quot;&quot;&quot; from typing import Dict, Any, Tuple, Optional, List import numpy as np import pandas as pd import logging logger = logging.getLogger(__name__) # A simple, documented result schema for detector functions. # Each detector returns a dict with these keys (guaranteed): # - &#39;mask&#39;: pd.Series[bool] same index as input rows; True means OUTLIER # - &#39;score&#39;: pd.Series or pd.DataFrame numeric score (bigger usually means more anomalous) # - &#39;method&#39;: short string # - &#39;params&#39;: dict of parameters used # - &#39;explanation&#39;: short textual note about interpretation OutlierResult = Dict[str, Any] def ensure_dataframe(X) -&gt; pd.DataFrame: &quot;&quot;&quot; Convert input into a pandas DataFrame with a stable integer index. Accepts: pd.DataFrame, np.ndarray, list-of-lists, pd.Series. Returns DataFrame with numeric column names if necessary. &quot;&quot;&quot; if isinstance(X, pd.DataFrame): df = X.copy() elif isinstance(X, pd.Series): df = X.to_frame() else: # try to coerce df = pd.DataFrame(X) # if no index or non-unique, reset if df.index is None or not df.index.is_unique: df = df.reset_index(drop=True) # name numeric columns if unnamed df.columns = [str(c) for c in df.columns] return df def numeric_only(df: pd.DataFrame, return_cols: bool = False) -&gt; pd.DataFrame: &quot;&quot;&quot; Select numeric columns and warn if non-numeric columns are dropped. If no numeric columns found raises ValueError. &quot;&quot;&quot; df = ensure_dataframe(df) numeric_df = df.select_dtypes(include=[&quot;number&quot;]).copy() non_numeric = [c for c in df.columns if c not in numeric_df.columns] if non_numeric: logger.debug(&quot;Dropping non-numeric columns for numeric-only detectors: %s&quot;, non_numeric) if numeric_df.shape[1] == 0: raise ValueError(&quot;No numeric columns available for numeric detectors. Consider encoding categoricals.&quot;) if return_cols: return numeric_df, list(numeric_df.columns) return numeric_df def handle_missing(df: pd.DataFrame, strategy: str = &quot;drop&quot;, fill_value: Optional[float] = None) -&gt; pd.DataFrame: &quot;&quot;&quot; Handle missing values in data before passing to detectors. Parameters ---------- df : DataFrame strategy : {&#39;drop&#39;, &#39;mean&#39;, &#39;median&#39;, &#39;zero&#39;, &#39;constant&#39;, &#39;keep&#39;} - &#39;drop&#39; : drop rows with any NaN (useful when most values are present) - &#39;mean&#39; : fill numeric columns with mean - &#39;median&#39; : fill numeric with median - &#39;zero&#39; : fill with 0 - &#39;constant&#39; : fill with supplied fill_value - &#39;keep&#39; : keep NaNs (many detectors can handle NaN rows implicitly) fill_value : numeric (used when strategy==&#39;constant&#39;) Returns ------- DataFrame cleaned according to strategy. Original index preserved. Notes ----- - Some detectors (LOF, IsolationForest) do NOT accept NaNs; choose strategy accordingly. &quot;&quot;&quot; df = df.copy() if strategy == &quot;drop&quot;: return df.dropna(axis=0, how=&quot;any&quot;) elif strategy == &quot;mean&quot;: return df.fillna(df.mean()) elif strategy == &quot;median&quot;: return df.fillna(df.median()) elif strategy == &quot;zero&quot;: return df.fillna(0) elif strategy == &quot;constant&quot;: if fill_value is None: raise ValueError(&quot;fill_value must be provided for strategy=&#39;constant&#39;&quot;) return df.fillna(fill_value) elif strategy == &quot;keep&quot;: return df else: raise ValueError(f&quot;Unknown missing value strategy: {strategy}&quot;) def robust_scale(df: pd.DataFrame) -&gt; pd.DataFrame: &quot;&quot;&quot; Scale numeric columns using median and IQR (robust to outliers). Returns a DataFrame of same shape with scaled values. &quot;&quot;&quot; df = numeric_only(df) med = df.median() q1 = df.quantile(0.25) q3 = df.quantile(0.75) iqr = q3 - q1 # avoid division by zero iqr_replaced = iqr.replace(0, 1.0) return (df - med) / iqr_replaced def create_result(mask: pd.Series, score: pd.Series, method: str, params: Dict[str, Any], explanation: str) -&gt; OutlierResult: &quot;&quot;&quot; Wrap mask + score into the standard result dict. &quot;&quot;&quot; # ensure index alignment if not mask.index.equals(score.index): # try to reindex score = score.reindex(mask.index) return { &quot;mask&quot;: mask.astype(bool), &quot;score&quot;: score, &quot;method&quot;: method, &quot;params&quot;: params, &quot;explanation&quot;: explanation, } def summarize_results(results: Dict[str, OutlierResult]) -&gt; pd.DataFrame: &quot;&quot;&quot; Given a dict of results keyed by method name, return a single DataFrame where each column is that method&#39;s boolean flag and another column is the score (if numeric). Also returns a short per-row summary like how many detectors flagged the row. &quot;&quot;&quot; # Collect masks and scores masks = {} scores = {} for k, r in results.items(): masks[f&quot;{k}_flag&quot;] = r[&quot;mask&quot;].astype(int) # flatten score: if DataFrame use mean across columns sc = r[&quot;score&quot;] if isinstance(sc, pd.DataFrame): sc = sc.mean(axis=1) scores[f&quot;{k}_score&quot;] = sc masks_df = pd.DataFrame(masks) scores_df = pd.DataFrame(scores) combined = pd.concat([masks_df, scores_df], axis=1) combined.index = next(iter(results.values()))[&quot;mask&quot;].index combined[&quot;n_flags&quot;] = masks_df.sum(axis=1) combined[&quot;any_flag&quot;] = combined[&quot;n_flags&quot;] &gt; 0 return combined def recommend_methods(X: pd.DataFrame) -&gt; List[str]: &quot;&quot;&quot; Heuristic recommender: returns a short list of methods to try depending on data shape. Rules (simple heuristics): - single numeric column: [&#39;iqr&#39;, &#39;modified_z&#39;] - low-dimensional (n_features &lt;= 10) and numeric: [&#39;mahalanobis&#39;,&#39;lof&#39;,&#39;isolation_forest&#39;] - high-dimensional (n_features &gt; 10): [&#39;isolation_forest&#39;,&#39;pca&#39;,&#39;autoencoder&#39;] &quot;&quot;&quot; df = ensure_dataframe(X) n_features = df.select_dtypes(include=[&quot;number&quot;]).shape[1] if n_features == 0: raise ValueError(&quot;No numeric features to recommend methods for&quot;) if n_features == 1: return [&quot;iqr&quot;, &quot;modified_z&quot;] elif n_features &lt;= 10: return [&quot;mahalanobis&quot;, &quot;lof&quot;, &quot;isolation_forest&quot;] else: return [&quot;isolation_forest&quot;, &quot;pca&quot;, &quot;autoencoder&quot;] # --------------------------- # File: outlier_detection/statistical.py # --------------------------- &quot;&quot;&quot; Statistical / univariate outlier detectors. Each function focuses on single-dimension input (pd.Series) or will operate column-wise if given a DataFrame (then returns DataFrame of scores / masks). &quot;&quot;&quot; from typing import Union import numpy as np import pandas as pd from scipy import stats from .utils import create_result, numeric_only def _as_series(x: Union[pd.Series, pd.DataFrame], col: str = None) -&gt; pd.Series: if isinstance(x, pd.DataFrame): if col is None: raise ValueError(&quot;If passing DataFrame, must pass column name&quot;) return x[col] return x def z_score_method(x: Union[pd.Series, pd.DataFrame], threshold: float = 3.0) -&gt; OutlierResult: &quot;&quot;&quot; Z-Score method (univariate) Math: z = (x - mean) / std Flag where |z| &gt; threshold. Applicability: single numeric column, approximately normal distribution. Not robust to heavy-tailed distributions. Returns OutlierResult with score = |z| (higher =&gt; more anomalous). &quot;&quot;&quot; if isinstance(x, pd.DataFrame): # apply per-column and return a DataFrame score masks = pd.DataFrame(index=x.index) scores = pd.DataFrame(index=x.index) for c in x.columns: res = z_score_method(x[c], threshold=threshold) masks[c] = res[&quot;mask&quot;].astype(int) scores[c] = res[&quot;score&quot;] # Derive a combined mask: any column flagged mask_any = masks.sum(axis=1) &gt; 0 combined_score = scores.mean(axis=1) return create_result(mask_any, combined_score, &quot;z_score_dataframe&quot;, {&quot;threshold&quot;: threshold}, &quot;Applied z-score per-column and combined by mean score and any-flag&quot;) s = x.dropna() if s.shape[0] == 0: mask = pd.Series([False]*len(x), index=x.index) score = pd.Series([0.0]*len(x), index=x.index) return create_result(mask, score, &quot;z_score&quot;, {&quot;threshold&quot;: threshold}, &quot;Empty or all-NaN series&quot;) mu = s.mean() sigma = s.std(ddof=0) if sigma == 0: score = pd.Series(0.0, index=x.index) mask = pd.Series(False, index=x.index) explanation = &quot;Zero variance: no z-score possible&quot; return create_result(mask, score, &quot;z_score&quot;, {&quot;threshold&quot;: threshold}, explanation) z = (x - mu) / sigma absz = z.abs() mask = absz &gt; threshold score = absz.fillna(0.0) explanation = f&quot;z-score with mean={mu:.4g}, std={sigma:.4g}; flag |z|&gt;{threshold}&quot; return create_result(mask, score, &quot;z_score&quot;, {&quot;threshold&quot;: threshold}, explanation) def modified_z_score(x: Union[pd.Series, pd.DataFrame], threshold: float = 3.5) -&gt; OutlierResult: &quot;&quot;&quot; Modified Z-score using median and MAD (robust to extreme values). Formula: M_i = 0.6745 * (x_i - median) / MAD Where MAD = median(|x_i - median|) Recommended threshold: 3.5 (common in literature) &quot;&quot;&quot; if isinstance(x, pd.DataFrame): masks = pd.DataFrame(index=x.index) scores = pd.DataFrame(index=x.index) for c in x.columns: res = modified_z_score(x[c], threshold=threshold) masks[c] = res[&quot;mask&quot;].astype(int) scores[c] = res[&quot;score&quot;] mask_any = masks.sum(axis=1) &gt; 0 combined_score = scores.mean(axis=1) return create_result(mask_any, combined_score, &quot;modified_z_dataframe&quot;, {&quot;threshold&quot;: threshold}, &quot;Applied modified z per-column and combined&quot;) s = x.dropna() if len(s) == 0: return create_result(pd.Series(False, index=x.index), pd.Series(0.0, index=x.index), &quot;modified_z&quot;, {&quot;threshold&quot;: threshold}, &quot;empty&quot;) med = np.median(s) mad = np.median(np.abs(s - med)) if mad == 0: # all equal or too small score = pd.Series(0.0, index=x.index) mask = pd.Series(False, index=x.index) return create_result(mask, score, &quot;modified_z&quot;, {&quot;threshold&quot;: threshold}, &quot;mad==0: no variation&quot;) M = 0.6745 * (x - med) / mad score = M.abs().fillna(0.0) mask = score &gt; threshold return create_result(mask, score, &quot;modified_z&quot;, {&quot;threshold&quot;: threshold, &quot;median&quot;: med, &quot;mad&quot;: mad}, &quot;Robust modified z-score; higher =&gt; more anomalous&quot;) def iqr_method(x: Union[pd.Series, pd.DataFrame], k: float = 1.5) -&gt; OutlierResult: &quot;&quot;&quot; IQR (boxplot) method. Flags points outside [Q1 - k*IQR, Q3 + k*IQR]. k=1.5 is common; use larger k for fewer false positives. &quot;&quot;&quot; if isinstance(x, pd.DataFrame): masks = pd.DataFrame(index=x.index) scores = pd.DataFrame(index=x.index) for c in x.columns: res = iqr_method(x[c], k=k) masks[c] = res[&quot;mask&quot;].astype(int) scores[c] = res[&quot;score&quot;] mask_any = masks.sum(axis=1) &gt; 0 combined_score = scores.mean(axis=1) return create_result(mask_any, combined_score, &quot;iqr_dataframe&quot;, {&quot;k&quot;: k}, &quot;Applied IQR per column&quot;) s = x.dropna() if s.shape[0] == 0: return create_result(pd.Series(False, index=x.index), pd.Series(0.0, index=x.index), &quot;iqr&quot;, {&quot;k&quot;: k}, &quot;empty&quot;) q1 = np.percentile(s, 25) q3 = np.percentile(s, 75) iqr = q3 - q1 lower = q1 - k * iqr upper = q3 + k * iqr mask = (x &lt; lower) | (x &gt; upper) # score: distance from nearest fence normalized by iqr (if iqr==0 use abs distance) if iqr == 0: score = (x - q1).abs().fillna(0.0) else: score = pd.Series(0.0, index=x.index) score[x &lt; lower] = ((lower - x[x &lt; lower]) / (iqr + 1e-12)) score[x &gt; upper] = ((x[x &gt; upper] - upper) / (iqr + 1e-12)) return create_result(mask.fillna(False), score.fillna(0.0), &quot;iqr&quot;, {&quot;k&quot;: k, &quot;q1&quot;: q1, &quot;q3&quot;: q3}, f&quot;IQR fences [{lower:.4g}, {upper:.4g}]&quot;) def grubbs_test(x: Union[pd.Series, pd.DataFrame], alpha: float = 0.05) -&gt; OutlierResult: &quot;&quot;&quot; Grubbs&#39; test for a single outlier (requires approx normality). This test is intended to *detect one outlier at a time*. Use iteratively (recompute after removing detected outlier) if you expect multiple outliers, but be careful with multiplicity adjustments. Returns mask with at most one True (the most extreme point) unless alpha is very large. &quot;&quot;&quot; # For simplicity operate only on a single series. If DataFrame provided, # run per-column and combine (like other funcs) if isinstance(x, pd.DataFrame): masks = pd.DataFrame(index=x.index) scores = pd.DataFrame(index=x.index) for c in x.columns: res = grubbs_test(x[c], alpha=alpha) masks[c] = res[&quot;mask&quot;].astype(int) scores[c] = res[&quot;score&quot;] mask_any = masks.sum(axis=1) &gt; 0 combined_score = scores.mean(axis=1) return create_result(mask_any, combined_score, &quot;grubbs_dataframe&quot;, {&quot;alpha&quot;: alpha}, &quot;Applied Grubbs per column&quot;) from math import sqrt s = x.dropna() n = len(s) if n &lt; 3: return create_result(pd.Series(False, index=x.index), pd.Series(0.0, index=x.index), &quot;grubbs&quot;, {&quot;alpha&quot;: alpha}, &quot;n&lt;3: cannot run&quot;) mean = s.mean() std = s.std(ddof=0) if std == 0: return create_result(pd.Series(False, index=x.index), pd.Series(0.0, index=x.index), &quot;grubbs&quot;, {&quot;alpha&quot;: alpha}, &quot;zero std&quot;) # compute G statistic for max dev deviations = (s - mean).abs() max_idx = deviations.idxmax() G = deviations.loc[max_idx] / std # critical value from t-distribution t_crit = stats.t.ppf(1 - alpha / (2 * n), n - 2) G_crit = ((n - 1) / sqrt(n)) * (t_crit / sqrt(n - 2 + t_crit ** 2)) mask = pd.Series(False, index=x.index) mask.loc[max_idx] = G &gt; G_crit score = pd.Series(0.0, index=x.index) score.loc[max_idx] = float(G) explanation = f&quot;G={G:.4g}, Gcrit={G_crit:.4g}, alpha={alpha}&quot; return create_result(mask, score, &quot;grubbs&quot;, {&quot;alpha&quot;: alpha, &quot;G&quot;: G, &quot;Gcrit&quot;: G_crit}, explanation) # --------------------------- # File: outlier_detection/distance_density.py # --------------------------- &quot;&quot;&quot; Distance and density based detectors (multivariate-capable). Functions generally accept a numeric DataFrame X and return OutlierResult. &quot;&quot;&quot; from sklearn.neighbors import LocalOutlierFactor, NearestNeighbors from sklearn.cluster import DBSCAN from sklearn.covariance import EmpiricalCovariance from .utils import ensure_dataframe, create_result, numeric_only def lof_method(X, n_neighbors: int = 20, contamination: float = 0.05) -&gt; OutlierResult: &quot;&quot;&quot; Local Outlier Factor (LOF). Returns score = -lof. LOF API returns negative_outlier_factor_. We negate so higher score =&gt; more anomalous. Applicability: medium-dimensional data, clusters of varying density. Beware: LOF does not provide a predictable probabilistic threshold. &quot;&quot;&quot; X = ensure_dataframe(X) Xnum = numeric_only(X) if Xnum.shape[0] &lt; 2: return create_result(pd.Series(False, index=X.index), pd.Series(0.0, index=X.index), &quot;lof&quot;, {&quot;n_neighbors&quot;: n_neighbors}, &quot;too few samples&quot;) lof = LocalOutlierFactor(n_neighbors=min(n_neighbors, max(1, Xnum.shape[0]-1)), contamination=contamination) y = lof.fit_predict(Xnum) negative_factor = lof.negative_outlier_factor_ # higher -&gt; more anomalous score = (-negative_factor) score = pd.Series(score, index=Xnum.index) mask = pd.Series(y == -1, index=Xnum.index) return create_result(mask, score, &quot;lof&quot;, {&quot;n_neighbors&quot;: n_neighbors, &quot;contamination&quot;: contamination}, &quot;LOF: higher score more anomalous&quot;) def knn_distance_method(X, k: int = 5) -&gt; OutlierResult: &quot;&quot;&quot; k-NN distance based scoring: compute distance to k-th nearest neighbor. Points with large k-distance are candidate outliers. Returns score = k-distance (bigger =&gt; more anomalous). &quot;&quot;&quot; X = ensure_dataframe(X) Xnum = numeric_only(X) if Xnum.shape[0] &lt; k + 1: return create_result(pd.Series(False, index=X.index), pd.Series(0.0, index=X.index), &quot;knn_distance&quot;, {&quot;k&quot;: k}, &quot;too few samples&quot;) nbrs = NearestNeighbors(n_neighbors=k + 1).fit(Xnum) distances, _ = nbrs.kneighbors(Xnum) # distances[:, 0] is zero (self). take k-th neighbor kdist = distances[:, k] score = pd.Series(kdist, index=Xnum.index) # threshold: e.g., mean + 2*std thr = score.mean() + 2 * score.std() mask = score &gt; thr return create_result(mask, score, &quot;knn_distance&quot;, {&quot;k&quot;: k, &quot;threshold&quot;: thr}, &quot;k-distance method&quot;) def mahalanobis_method(X, threshold_p: float = 0.01) -&gt; OutlierResult: &quot;&quot;&quot; Mahalanobis distance based detection. Computes D^2 for each point. One can threshold by chi-square quantile with df=n_features: P(D^2 &gt; thresh) = threshold_p. We return score = D^2. Applicability: data approximately elliptical (multivariate normal-ish). &quot;&quot;&quot; X = ensure_dataframe(X) Xnum = numeric_only(X) n, d = Xnum.shape if n &lt;= d: # covariance ill-conditioned; apply shrinkage or PCA beforehand explanation = &quot;n &lt;= n_features: covariance may be singular, consider PCA or regularization&quot; else: explanation = &quot;&quot; cov = EmpiricalCovariance().fit(Xnum) mahal = cov.mahalanobis(Xnum) score = pd.Series(mahal, index=Xnum.index) # default threshold: chi2 quantile from scipy.stats import chi2 thr = chi2.ppf(1 - threshold_p, df=d) if d &gt; 0 else np.inf mask = score &gt; thr return create_result(mask, score, &quot;mahalanobis&quot;, {&quot;threshold_p&quot;: threshold_p, &quot;chi2_thr&quot;: float(thr)}, explanation) def dbscan_method(X, eps: float = 0.5, min_samples: int = 5) -&gt; OutlierResult: &quot;&quot;&quot; DBSCAN clusterer: points labeled -1 are considered noise -&gt; outliers. Applicability: non-spherical clusters, variable density; choose eps carefully. &quot;&quot;&quot; X = ensure_dataframe(X) Xnum = numeric_only(X) if Xnum.shape[0] &lt; min_samples: return create_result(pd.Series(False, index=X.index), pd.Series(0.0, index=X.index), &quot;dbscan&quot;, {&quot;eps&quot;: eps, &quot;min_samples&quot;: min_samples}, &quot;too few samples&quot;) db = DBSCAN(eps=eps, min_samples=min_samples).fit(Xnum) labels = db.labels_ mask = pd.Series(labels == -1, index=Xnum.index) # score: negative of cluster size (noise points get score 1) # To keep simple: noise -&gt; 1, else 0 score = pd.Series((labels == -1).astype(float), index=Xnum.index) return create_result(mask, score, &quot;dbscan&quot;, {&quot;eps&quot;: eps, &quot;min_samples&quot;: min_samples}, &quot;DBSCAN noise points flagged&quot;) # --------------------------- # File: outlier_detection/model_based.py # --------------------------- &quot;&quot;&quot; Model-based detectors: tree ensembles, SVM boundary, PCA reconstruction, GMM These functions are intended for multivariate numeric data. &quot;&quot;&quot; from sklearn.ensemble import IsolationForest from sklearn.svm import OneClassSVM from sklearn.decomposition import PCA from sklearn.mixture import GaussianMixture from sklearn.covariance import EllipticEnvelope from .utils import ensure_dataframe, numeric_only, create_result def isolation_forest_method(X, contamination: float = 0.05, random_state: int = 42) -&gt; OutlierResult: &quot;&quot;&quot; Isolation Forest Returns mask and anomaly score (higher =&gt; more anomalous). Good general-purpose method for medium-to-high dimensional data. &quot;&quot;&quot; X = ensure_dataframe(X) Xnum = numeric_only(X) if Xnum.shape[0] &lt; 2: return create_result(pd.Series(False, index=X.index), pd.Series(0.0, index=X.index), &quot;isolation_forest&quot;, {&quot;contamination&quot;: contamination}, &quot;too few samples&quot;) iso = IsolationForest(contamination=contamination, random_state=random_state) iso.fit(Xnum) pred = iso.predict(Xnum) # decision_function: higher -&gt; more normal, so we invert raw_score = -iso.decision_function(Xnum) score = pd.Series(raw_score, index=Xnum.index) mask = pd.Series(pred == -1, index=Xnum.index) return create_result(mask, score, &quot;isolation_forest&quot;, {&quot;contamination&quot;: contamination}, &quot;IsolationForest: inverted decision function as score&quot;) def one_class_svm_method(X, kernel: str = &quot;rbf&quot;, nu: float = 0.05, gamma: str = &quot;scale&quot;) -&gt; OutlierResult: &quot;&quot;&quot; One-Class SVM for boundary-based anomaly detection. Carefully tune nu and gamma; not robust to large datasets without subsampling. &quot;&quot;&quot; X = ensure_dataframe(X) Xnum = numeric_only(X) if Xnum.shape[0] &lt; 5: return create_result(pd.Series(False, index=X.index), pd.Series(0.0, index=X.index), &quot;one_class_svm&quot;, {&quot;nu&quot;: nu}, &quot;too few samples&quot;) ocsvm = OneClassSVM(kernel=kernel, nu=nu, gamma=gamma) ocsvm.fit(Xnum) pred = ocsvm.predict(Xnum) # decision_function: positive =&gt; inside boundary (normal); invert raw_score = -ocsvm.decision_function(Xnum) score = pd.Series(raw_score, index=Xnum.index) mask = pd.Series(pred == -1, index=Xnum.index) return create_result(mask, score, &quot;one_class_svm&quot;, {&quot;nu&quot;: nu, &quot;kernel&quot;: kernel}, &quot;OneClassSVM: invert decision_function for anomaly score&quot;) def pca_reconstruction_error(X, n_components: int = None, explained_variance: float = None, threshold: float = None) -&gt; OutlierResult: &quot;&quot;&quot; PCA-based reconstruction error. If n_components not set, choose the minimum components to reach explained_variance (if provided). Otherwise uses min(n_features, 2). Score: squared reconstruction error per sample. Default threshold: mean+3*std. &quot;&quot;&quot; X = ensure_dataframe(X) Xnum = numeric_only(X) n, d = Xnum.shape if n == 0 or d == 0: return create_result(pd.Series(False, index=X.index), pd.Series(0.0, index=X.index), &quot;pca_recon&quot;, {}, &quot;empty data&quot;) if n_components is None: if explained_variance is not None: temp_pca = PCA(n_components=min(n, d)) temp_pca.fit(Xnum) cum = np.cumsum(temp_pca.explained_variance_ratio_) n_components = int(np.searchsorted(cum, explained_variance) + 1) n_components = max(1, n_components) else: n_components = min(2, d) pca = PCA(n_components=n_components) proj = pca.fit_transform(Xnum) recon = pca.inverse_transform(proj) errors = ((Xnum - recon) ** 2).sum(axis=1) score = pd.Series(errors, index=Xnum.index) if threshold is None: threshold = score.mean() + 3 * score.std() mask = score &gt; threshold return create_result(mask, score, &quot;pca_recon&quot;, {&quot;n_components&quot;: n_components, &quot;threshold&quot;: float(threshold)}, &quot;PCA reconstruction error&quot;) def gmm_method(X, n_components: int = 2, contamination: float = 0.05) -&gt; OutlierResult: &quot;&quot;&quot; Gaussian Mixture Model based anomaly score (log-likelihood). Score: negative log-likelihood (bigger =&gt; less likely =&gt; more anomalous). Threshold: empirical quantile of scores. &quot;&quot;&quot; X = ensure_dataframe(X) Xnum = numeric_only(X) if Xnum.shape[0] &lt; n_components: return create_result(pd.Series(False, index=X.index), pd.Series(0.0, index=X.index), &quot;gmm&quot;, {}, &quot;too few samples&quot;) gmm = GaussianMixture(n_components=n_components) gmm.fit(Xnum) logprob = gmm.score_samples(Xnum) score = pd.Series(-logprob, index=Xnum.index) thr = score.quantile(1 - contamination) mask = score &gt; thr return create_result(mask, score, {&quot;n_components&quot;: n_components, &quot;threshold&quot;: float(thr)}, &quot;gmm&quot;, &quot;GMM negative log-likelihood&quot;) def elliptic_envelope_method(X, contamination: float = 0.05) -&gt; OutlierResult: &quot;&quot;&quot; EllipticEnvelope fits a robust covariance (assumes data come from a Gaussian-like ellipse). Flags outliers outside the ellipse. &quot;&quot;&quot; X = ensure_dataframe(X) Xnum = numeric_only(X) ee = EllipticEnvelope(contamination=contamination) ee.fit(Xnum) pred = ee.predict(Xnum) # decision_function: larger -&gt; more normal; invert raw_score = -ee.decision_function(Xnum) score = pd.Series(raw_score, index=Xnum.index) mask = pd.Series(pred == -1, index=Xnum.index) return create_result(mask, score, &quot;elliptic_envelope&quot;, {&quot;contamination&quot;: contamination}, &quot;EllipticEnvelope&quot;) # --------------------------- # File: outlier_detection/deep_learning.py # --------------------------- &quot;&quot;&quot; Deep learning based detectors (AutoEncoder, VAE). These require TensorFlow/Keras installed. If not present, importing this module will raise an informative ImportError. Design: a training function accepts X (numpy or DataFrame) and returns a callable `score_fn(X_new) -&gt; pd.Series` plus a threshold selection helper. &quot;&quot;&quot; from typing import Callable import numpy as np import pandas as pd # lazy import to avoid hard TF dependency if user doesn&#39;t need it try: import tensorflow as tf from tensorflow.keras import layers, models, backend as K except Exception as e: raise ImportError(&quot;TensorFlow / Keras is required for deep_learning module. Install with `pip install tensorflow`. Error: &quot; + str(e)) from .utils import ensure_dataframe, create_result def _build_autoencoder(input_dim: int, latent_dim: int = 8, hidden_units=(64, 32)) -&gt; models.Model: inp = layers.Input(shape=(input_dim,)) x = inp for h in hidden_units: x = layers.Dense(h, activation=&#39;relu&#39;)(x) z = layers.Dense(latent_dim, activation=&#39;relu&#39;, name=&#39;latent&#39;)(x) x = z for h in reversed(hidden_units): x = layers.Dense(h, activation=&#39;relu&#39;)(x) out = layers.Dense(input_dim, activation=&#39;linear&#39;)(x) ae = models.Model(inp, out) return ae def autoencoder_method(X, latent_dim: int = 8, hidden_units=(128, 64), epochs: int = 50, batch_size: int = 32, validation_split: float = 0.1, threshold_method: str = &#39;quantile&#39;, threshold_val: float = 0.99, verbose: int = 0) -&gt; OutlierResult: &quot;&quot;&quot; Train an AutoEncoder on X and compute reconstruction error as anomaly score. Parameters ---------- X : DataFrame or numpy array (numeric) threshold_method : &#39;quantile&#39; or &#39;mean_std&#39; threshold_val : if quantile -&gt; e.g. 0.99 means top 1% flagged; if mean_std -&gt; number of stds Returns ------- OutlierResult where score = reconstruction error and mask = score &gt; threshold Notes ----- - This trains on the entire provided X. For actual anomaly detection, it&#39;s common to train the autoencoder only on &quot;normal&quot; data. If you have labels, pass only normal subset for training. - Requires careful scaling of inputs before training (robust_scale recommended). &quot;&quot;&quot; Xdf = ensure_dataframe(X) Xnum = Xdf.select_dtypes(include=[&#39;number&#39;]).fillna(0.0) input_dim = Xnum.shape[1] if input_dim == 0: return create_result(pd.Series(False, index=Xdf.index), pd.Series(0.0, index=Xdf.index), &quot;autoencoder&quot;, {}, &quot;no numeric columns&quot;) # convert to numpy arr = Xnum.values.astype(np.float32) ae = _build_autoencoder(input_dim=input_dim, latent_dim=latent_dim, hidden_units=hidden_units) ae.compile(optimizer=&#39;adam&#39;, loss=&#39;mse&#39;) ae.fit(arr, arr, epochs=epochs, batch_size=batch_size, validation_split=validation_split, verbose=verbose) recon = ae.predict(arr) errors = np.mean((arr - recon) ** 2, axis=1) score = pd.Series(errors, index=Xdf.index) if threshold_method == &#39;quantile&#39;: thr = float(score.quantile(threshold_val)) else: thr = float(score.mean() + threshold_val * score.std()) mask = score &gt; thr return create_result(mask, score, &quot;autoencoder&quot;, {&quot;latent_dim&quot;: latent_dim, &quot;threshold&quot;: thr}, &quot;AutoEncoder reconstruction error&quot;) def vae_method(X, latent_dim: int = 8, hidden_units=(128, 64), epochs: int = 50, batch_size: int = 32, threshold_method: str = &#39;quantile&#39;, threshold_val: float = 0.99, verbose: int = 0) -&gt; OutlierResult: &quot;&quot;&quot; Variational Autoencoder (VAE) anomaly detection. Implementation note: VAE is more involved; here we provide a simple implementation that uses reconstruction error as score. For strict probabilistic anomaly scoring one would use the ELBO / likelihood; this minimal implementation keeps it practical. &quot;&quot;&quot; # For brevity we reuse autoencoder path (a more complete VAE impl is possible) return autoencoder_method(X, latent_dim=latent_dim, hidden_units=hidden_units, epochs=epochs, batch_size=batch_size, threshold_method=threshold_method, threshold_val=threshold_val, verbose=verbose) # --------------------------- # File: outlier_detection/ensemble.py # --------------------------- &quot;&quot;&quot; Combine multiple detectors and produce an aggregated report. Provides strategies: union, intersection, majority voting, weighted sum of normalized scores. &quot;&quot;&quot; from typing import List, Dict import numpy as np import pandas as pd from .utils import ensure_dataframe, create_result def normalize_scores(scores: pd.DataFrame) -&gt; pd.DataFrame: &quot;&quot;&quot;Min-max normalize each score column to [0,1].&quot;&quot;&quot; sc = scores.copy() for c in sc.columns: col = sc[c] mn = col.min() mx = col.max() if mx == mn: sc[c] = 0.0 else: sc[c] = (col - mn) / (mx - mn) return sc def aggregate_scores(results: Dict[str, Dict], method: str = &#39;weighted&#39;, weights: Dict[str, float] = None) -&gt; Dict: &quot;&quot;&quot; Aggregate multiple OutlierResult dictionaries produced by detectors. Returns an OutlierResult-like dict with: - mask (final boolean by threshold on aggregate score), - score (aggregate numeric score) Aggregation methods: - &#39;union&#39; : any detector flagged =&gt; outlier (score = max of normalized scores) - &#39;intersection&#39; : flagged by all detectors =&gt; outlier - &#39;majority&#39; : flagged by &gt;50% detectors - &#39;weighted&#39; : weighted sum of normalized scores (weights provided or equal) &quot;&quot;&quot; # collect masks and scores into DataFrames masks = pd.DataFrame({k: v[&#39;mask&#39;].astype(int) for k, v in results.items()}) raw_scores = pd.DataFrame({k: (v[&#39;score&#39;] if isinstance(v[&#39;score&#39;], pd.Series) else pd.Series(v[&#39;score&#39;])) for k, v in results.items()}) raw_scores.index = masks.index norm_scores = normalize_scores(raw_scores) if method == &#39;union&#39;: agg_score = norm_scores.max(axis=1) elif method == &#39;intersection&#39;: agg_score = norm_scores.min(axis=1) elif method == &#39;majority&#39;: agg_score = masks.sum(axis=1) / max(1, masks.shape[1]) elif method == &#39;weighted&#39;: if weights is None: weights = {k: 1.0 for k in results.keys()} # align weights w = pd.Series({k: weights.get(k, 1.0) for k in results.keys()}) # make sure weights sum to 1 w = w / w.sum() agg_score = (norm_scores * w).sum(axis=1) else: raise ValueError(&quot;Unknown aggregation method&quot;) # default threshold: 0.5 mask = agg_score &gt; 0.5 return create_result(mask, agg_score, f&quot;ensemble_{method}&quot;, {&quot;method&quot;: method}, &quot;Aggregated ensemble score&quot;) def ensemble_methods(X, method_list: List[str] = None, method_params: Dict = None) -&gt; Dict[str, Dict]: &quot;&quot;&quot; Convenience: run multiple detectors by name and return dict of results. method_list: list of names from [&#39;iqr&#39;,&#39;modified_z&#39;,&#39;z_score&#39;,&#39;lof&#39;,&#39;mahalanobis&#39;,&#39;isolation_forest&#39;, ...] method_params: optional dict mapping method name to params &quot;&quot;&quot; from . import statistical, distance_density, model_based, deep_learning X = ensure_dataframe(X) if method_list is None: method_list = [&#39;iqr&#39;, &#39;modified_z&#39;, &#39;isolation_forest&#39;, &#39;lof&#39;] if method_params is None: method_params = {} results = {} for m in method_list: params = method_params.get(m, {}) try: if m == &#39;iqr&#39;: results[m] = statistical.iqr_method(X, **params) elif m == &#39;modified_z&#39;: results[m] = statistical.modified_z_score(X, **params) elif m == &#39;z_score&#39;: results[m] = statistical.z_score_method(X, **params) elif m == &#39;lof&#39;: results[m] = distance_density.lof_method(X, **params) elif m == &#39;mahalanobis&#39;: results[m] = distance_density.mahalanobis_method(X, **params) elif m == &#39;dbscan&#39;: results[m] = distance_density.dbscan_method(X, **params) elif m == &#39;knn&#39;: results[m] = distance_density.knn_distance_method(X, **params) elif m == &#39;isolation_forest&#39;: results[m] = model_based.isolation_forest_method(X, **params) elif m == &#39;one_class_svm&#39;: results[m] = model_based.one_class_svm_method(X, **params) elif m == &#39;pca&#39;: results[m] = model_based.pca_reconstruction_error(X, **params) elif m == &#39;gmm&#39;: results[m] = model_based.gmm_method(X, **params) elif m == &#39;elliptic&#39;: results[m] = model_based.elliptic_envelope_method(X, **params) elif m == &#39;autoencoder&#39;: results[m] = deep_learning.autoencoder_method(X, **params) else: logger.warning(&quot;Unknown method requested: %s&quot;, m) except Exception as e: logger.exception(&quot;Method %s failed: %s&quot;, m, e) return results # --------------------------- # File: outlier_detection/visualization.py # --------------------------- &quot;&quot;&quot; Simple plotting helpers for quick inspection. Note: plotting is intentionally minimal; for report-quality figures users can adapt styles. The functions return the matplotlib Figure object so they can be further customized. &quot;&quot;&quot; import matplotlib.pyplot as plt from .utils import ensure_dataframe def plot_boxplot(series: pd.Series, show: bool = True): df = ensure_dataframe(series) col = df.columns[0] fig, ax = plt.subplots() ax.boxplot(df[col].dropna()) ax.set_title(f&quot;Boxplot: {col}&quot;) if show: plt.show() return fig def plot_pair_scatter(X, columns: list = None, show: bool = True): X = ensure_dataframe(X) if columns is not None: X = X[columns] cols = X.columns.tolist()[:4] # avoid huge plots fig, axes = plt.subplots(len(cols) - 1, len(cols) - 1, figsize=(4 * (len(cols) - 1), 4 * (len(cols) - 1))) for i in range(1, len(cols)): for j in range(i): ax = axes[i - 1, j] ax.scatter(X[cols[j]], X[cols[i]], s=8) ax.set_xlabel(cols[j]) ax.set_ylabel(cols[i]) fig.suptitle(&quot;Pairwise scatter (first 4 numeric cols)&quot;) if show: plt.show() return fig # --------------------------- # File: outlier_detection/cli.py # --------------------------- &quot;&quot;&quot; A very small CLI to run detectors on a CSV file and output a CSV report. Usage (example): python -m outlier_detection.cli detect input.csv output_report.csv --methods iqr,isolation_forest &quot;&quot;&quot; import argparse import pandas as pd from .ensemble import ensemble_methods, aggregate_scores def main(): parser = argparse.ArgumentParser(description=&#39;Outlier detection CLI&#39;) sub = parser.add_subparsers(dest=&#39;cmd&#39;) det = sub.add_parser(&#39;detect&#39;) det.add_argument(&#39;input_csv&#39;) det.add_argument(&#39;output_csv&#39;) det.add_argument(&#39;--methods&#39;, default=&#39;iqr,modified_z,isolation_forest,lof&#39;) args = parser.parse_args() df = pd.read_csv(args.input_csv) methods = args.methods.split(&#39;,&#39;) results = ensemble_methods(df, method_list=methods) agg = aggregate_scores(results, method=&#39;weighted&#39;) summary = pd.concat([pd.DataFrame({k: v[&#39;mask&#39;].astype(int) for k, v in results.items()}), pd.DataFrame({k: v[&#39;score&#39;] for k, v in results.items()})], axis=1) summary[&#39;ensemble_score&#39;] = agg[&#39;score&#39;] summary[&#39;ensemble_flag&#39;] = agg[&#39;mask&#39;].astype(int) summary.to_csv(args.output_csv, index=False) print(f&quot;Wrote report to {args.output_csv}&quot;) if __name__ == &#39;__main__&#39;: main()改成中文说明并返回代码给我
最新发布
08-27
&lt;think&gt;嗯,用户想用特定的操作符实现整数取反函数negate。只能使用!~&amp;、^|+&lt;&lt;、&gt;&gt;这些操作符。首先,我得回忆一下补码的知识,因为计算机中整数通常用补码表示。取反的话,应该就是求补码的负数,也就是取反加一。比如,5的二进制是0101,取反后是1010,再加一得到1011,也就是-5。 那如何用这些操作符来实现呢?可能需要用到按位取反和加一的操作。比如,对于x,取反可以表示为~x,然后加1,所以negate(x)应该是~x + 1。不过需要验证这个是否正确。 比如,假设x是5,二进制是0101~x就是1010(假设4位),加1就是1011,即-5。这样看起来是对的。但要注意的是,这里是否会有溢出或者边界情况的问题。比如,当x是0的时候,取反应该是0,因为~0-1,加1得到0。这也正确。 那用户提到的引用[1]里提到了取反后用补码运算,可能就是这个思路。根据引用[1],判断奇数位全为1时使用了构造掩码的方法,但这里的问题不同。不过补码的取反操作应该适用。 所以最终的实现应该是将输入x按位取反,然后加1。也就是返回~x + 1。这样就能得到x的负数了。但需要确保所有操作符都是允许的。用户允许的操作符包括~+,所以这个方法是可行的。 那代码部分的话,可能写成函数形式,比如: int negate(int x) { return ~x + 1; } 不过可能需要考虑其他情况吗?比如,当x是0的时候,~x +1确实是0。对于最小整数,比如-2147483648,取反的话会溢出,但根据补码的规则,这个数的负数还是它自己,因为补码无法表示正数的2147483648。但在这个实现中,~x +1对于x=-2147483648,~x是2147483647,加1变成2147483648,但由于int是32位有符号,这里会溢出,结果还是-2147483648。不过根据C语言的未定义行为,可能需要用其他方法处理。但用户可能只需要常规情况下的正确性,或者题目假设这种情况可以接受? 不过用户的问题可能只需要一般的取反方法,而上述代码在大多数情况下是正确的。所以可以这样实现。&lt;/think&gt;要使用指定的操作符实现整数取反函数 $negate(x)$,可以通过补码运算的性质来完成。根据补码的定义,一个数的负数等于其按位取反后加 $1$,即 $negate(x) = -x = \sim x + 1$。具体步骤如下: 1. **按位取反**:使用 `~` 操作符对输入 $x$ 的每一位取反。 2. **1**:对取反后的结果加 $1$,通过 `+` 操作符实现。 代码实现如下: ```c int negate(int x) { return ~x + 1; } ``` **验证示例**- 若 $x = 5$,二进制为 `0000...0101`,取反后为 `1111...1010`,加 $1$ 得到 `1111...1011`,即 $-5$。 - 若 $x = -3$,二进制为 `1111...1101`,取反后为 `0000...0010`,加 $1$ 得到 `0000...0011`,即 $3$[^1]。 **边界条件**- 当 $x = 0$ 时,结果为 $0$(`~0 + 1 = -1 + 1 = 0`)。 - 当 $x = TMin$(最小负数,如 `0x80000000`)时,结果为自身,这是补码的溢出特性。 相关问题
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值