featrs/featrs
حول
A Polars-native feature engineering library for Rust.
البيانات والتحليلاتما يمكنك فعله
- Scaling - StandardScaler - Z-score normalization (mean 0, variance 1)
- MinMaxScaler - Scale to [0, 1] or custom range
- RobustScaler - Scale using median and IQR (outlier-robust)
- MaxAbsScaler - Scale by maximum absolute value; training values map to [-1, 1], sparsity preserved
النمو المقاس للنجوم
- خلال 24 ساعة
- ٠
- خلال 7 أيام
- +١
- خلال 15 يومًا
- +٣
- خلال شهر
- جارٍ جمع السجل
تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.
README.md
الأصلfeatrs
Feature engineering library for Rust, inspired by scikit-learn.
Built on Polars — all transformations operate natively on DataFrame and preserve column names.
Read the write-up: why a feature engineering API designed for NumPy arrays changes when it moves to named Polars columns, and what
AutoScalerdecides per column, is at adityavikram.dev/blog/featrs-scikit-learn-for-rust.
Installation
[dependencies]
featrs = "0.6"
Quick start
use featrs::prelude::*;
let mut scaler = StandardScaler::new();
scaler.fit(data.clone())?;
let scaled = scaler.transform(data)?;
Features
| Category | Component | Description |
|---|---|---|
| Scaling | StandardScaler |
Z-score normalization (mean 0, variance 1) |
MinMaxScaler |
Scale to [0, 1] or custom range |
|
RobustScaler |
Scale using median and IQR (outlier-robust) | |
MaxAbsScaler |
Scale by maximum absolute value; training values map to [-1, 1], sparsity preserved |
|
AutoScaler |
Pick the scaler per column from the column's own statistics (sparsity, outliers, skew, kurtosis) | |
Winsorizer |
Clip extreme values at configurable quantiles (outlier capping) | |
OutlierClipper |
Clip outliers via IQR, Z-score, or MAD statistical fences | |
KBinsDiscretizer |
Bin continuous features into n_bins discrete bins (uniform, quantile, or k-means) as ordinal or one-hot |
|
| Normalization | Normalizer |
Row-wise L1, L2, or Max normalization |
Binarizer |
Threshold-based binarization; in Float64 columns, nulls and NaN pass through as null | |
| Encoding | OneHotEncoder |
Create binary dummy columns for categories; unseen categories error by default (HandleUnknown) |
LabelEncoder |
Encode labels as 0..n_classes-1 integers |
|
OrdinalEncoder |
Per-column category → integer encoding | |
CountEncoder |
Replace categories with their raw occurrence counts | |
FrequencyEncoder |
Replace categories with their observed relative frequencies | |
BinaryEncoder |
Encode categories as binary digit columns using max(1, ceil(log₂(n_categories))) columns |
|
TargetEncoder |
Replace categories with the smoothed mean of a supervised target | |
LeaveOneOutEncoder |
Replace categories with a leave-one-out supervised target mean (no self-leak on training rows) | |
CyclicalEncoder |
Sin/cos encoding for cyclical features (hour, month) | |
FeatureHasher |
Hash strings into a fixed number of buckets | |
StringCleaner |
Trim, normalize case, and regex-replace string values | |
RareCategoryGrouper |
Group rare and unseen categories into "Other" |
|
| Imputation | SimpleImputer |
Fill nulls with mean, median, mode, or constant |
AutoImputer |
Pick the imputation strategy per column from the column's null fraction and skew | |
MissingIndicator |
Binary columns marking where values were missing | |
| Feature Generation | PolynomialFeatures |
Generate polynomial and interaction features |
Lagger |
Create lag features for time-series forecasting | |
RollingAggregator |
Rolling window mean, std, min, max, sum | |
ExpandingAggregator |
Expanding (cumulative) window mean, sum, min, max, std | |
ExponentiallyWeightedMovingAverage |
EWMA mean, variance, and std with exponential decay | |
Difference |
Differencing (x[t] - x[t-1]) and percentage change |
|
DatetimeFeatures |
Extract year/month/weekday/quarter/… components from date columns | |
TimeSince |
Elapsed time from a reference timestamp ({column}_since_{unit}) in seconds…weeks |
|
HolidayEncoder |
Binary {column}_is_holiday indicator for a country's statutory holidays (US, GB, DE, FR, JP, IN) |
|
| Text | CharacterNGramVectorizer |
Character n-gram term-count features (char, or char-within-word-boundary) |
CountVectorizer |
Bag-of-words term counts from a tokenized text column | |
TFIDFVectorizer |
TF-IDF weights from a text column (word counts reweighted by inverse document frequency) | |
| Pipeline | Pipeline |
Sequentially chain multiple transformers |
ColumnTransformer |
Apply different transformers to different columns | |
FeatureUnion |
Apply every transformer to the full input and concatenate the outputs | |
ConditionalPipeline |
Route each column to a transformer by dtype, name pattern, or custom predicate | |
CachedPipeline |
Cache each step's output and replay it for a repeated input | |
| Selection | VarianceThreshold |
Remove low-variance features |
SelectKBest |
Select top-k features by statistical test (ANOVA F) | |
SelectPercentile |
Select the top N% of features by statistical test | |
CorrelationThreshold |
Drop features highly correlated with others | |
MutualInformationSelector |
Rank/select top-k features by mutual information with the target | |
| Auto | AutoTypeDetector |
Auto-detect column types (incl. numeric-string columns) and apply default transforms |
AutoPipeline |
Infer a preprocessing plan from the frame and assemble a fitted, inspectable Pipeline: cleaning, encoding, imputation and scaling |
|
| Schema | SchemaSpec / validate_schema |
Describe a transformer's required input columns and dtypes, check a frame before transforming, and report every mismatch in one error |
| Output schema | FeatureNamesOut |
Report the exact output column names, in order, that a fitted transformer's transform emits — without materialising data. Implemented by every transformer and threaded through Pipeline, ColumnTransformer, FeatureUnion, ConditionalPipeline, and CachedPipeline |
| Diagnostics | DataQualityReport |
Summarise nulls, per-column stats and outliers, cardinality, duplicate rows/columns, constant columns, and the preprocessing it recommends |
Examples
Every snippet is a fragment: it assumes a df: DataFrame is already in scope and
shows the transformer calls alone. Wrap the body in a function returning
Result<_, featrs::traits::Error> to run it as written.
StandardScaler
use featrs::prelude::*;
let mut scaler = StandardScaler::new();
scaler.fit(df.clone())?;
let scaled = scaler.transform(df)?;
AutoScaler
use featrs::prelude::*;
let mut scaler = AutoScaler::new();
scaler.fit(df.clone())?;
// Which scaler each Float64 column got, e.g. "StandardScaler+RobustScaler".
println!("{:?}", scaler.chosen_name());
let scaled = scaler.transform(df)?;
Inverse transforms
Invertible transformers implement InverseTransform, which maps output features
back to the input domain. Scalers, LogTransformer, PowerTransformer, and
QuantileTransformer support it; encoders, binarizers, discretizers, and feature
selectors do not. Roundtrips are approximate, so compare with a tolerance.
use featrs::prelude::*;
let mut scaler = StandardScaler::new();
scaler.fit(df.clone())?;
let scaled = scaler.transform(df.clone())?;
// Original units again, e.g. to read model predictions as raw values.
let restored = scaler.inverse_transform(scaled)?;
// Capability discovery for a transformer you did not construct yourself.
assert!(scaler.is_invertible());
Pipeline
use featrs::prelude::*;
let mut pipeline = Pipeline::new(vec![
("scale".into(), Box::new(StandardScaler::new())),
("poly".into(), Box::new(PolynomialFeatures::new(2)?)),
])?;
pipeline.fit(df.clone())?;
let result = pipeline.transform(df)?;
ColumnTransformer
use featrs::prelude::*;
let ct = ColumnTransformer::new(
vec![("scale".into(), Box::new(StandardScaler::new()), vec!["feat_a".into()])],
Remainder::Passthrough,
);
FeatureUnion
Every transformer receives the full input and their outputs are concatenated horizontally. Transformers that preserve their input column names collide, so pair the union with branches that emit distinct columns.
use featrs::prelude::*;
let mut union = FeatureUnion::new(vec![
(
"scaled_a".into(),
Box::new(ColumnTransformer::new(
vec![("s".into(), Box::new(StandardScaler::new()), vec!["feat_a".into()])],
Remainder::Drop,
)),
),
(
"scaled_b".into(),
Box::new(ColumnTransformer::new(
vec![("s".into(), Box::new(StandardScaler::new()), vec!["feat_b".into()])],
Remainder::Drop,
)),
),
])?;
union.fit(df.clone())?;
let result = union.transform(df)?;
ConditionalPipeline
Instead of naming the columns each transformer receives, supply rules.
Every column goes to the first rule that matches it, so a column is
transformed once and never duplicated. Columns no rule matches go to the
optional fallback and are dropped without one.
use featrs::prelude::*;
use featrs::pipeline::conditional_pipeline::ColumnPredicate;
let mut cp = ConditionalPipeline::new()
// Rules are tried in this order, so the name rule has to come before
// `IsString` to claim `user_id` on a string column.
.rule(ColumnPredicate::NameMatches(".*_id$".into()), Box::new(FeatureHasher::new(&["user_id"], 16)))
.rule(ColumnPredicate::IsFloat64, Box::new(StandardScaler::new()))
.rule(ColumnPredicate::IsString, Box::new(OneHotEncoder::new()))
.fallback(Box::new(MissingIndicator::all()));
cp.fit(df.clone())?;
let routed = cp.transform(df)?;
// Which transformer claimed which column, in frame order.
for (column, label) in cp.assignments().unwrap_or(&[]) {
println!("{column} -> {label}");
}
ColumnPredicate::Custom takes a Fn(&Column) -> bool + Send + Sync closure,
so data-dependent routing (cardinality, null fraction) works too. The closure
runs before any transformer and must not panic.
CachedPipeline
Wraps a Pipeline and remembers each step's output, so re-transforming an
input it has already seen replays the cached frames instead of recomputing
them. The key is the input's schema (column names + dtypes) plus row count:
cheap, but blind to value changes that leave the schema alone, so it cannot tell
one frame from another of the same shape and height — use it only for repeated
calls on inputs known to be identical, and call clear_cache() before
transforming a different frame of the same shape. Entries are bounded by
max_cache_entries (default 16, oldest evicted first); 0 disables caching.
use featrs::prelude::*;
let pipeline = Pipeline::new(vec![
("scale".into(), Box::new(StandardScaler::new())),
("poly".into(), Box::new(PolynomialFeatures::new(2)?)),
])?;
let mut cached = CachedPipeline::new(pipeline).max_cache_entries(4);
cached.fit(df.clone())?;
let first = cached.transform(df.clone())?; // computes and caches
let second = cached.transform(df)?; // replayed from the cache
assert_eq!(cached.cache_size(), 1);
assert!(second.equals_missing(&first));
// Before transforming a different frame of the same shape, drop the stale entries.
cached.clear_cache();
PolynomialFeatures (builder pattern)
use featrs::prelude::*;
let pf = PolynomialFeatures::builder()
.degree(3)
.include_bias(false)
.interaction_only(true)
.build()?;
Feature Selection
use featrs::prelude::*;
let mut vt = VarianceThreshold::new(0.01);
vt.fit(features.clone())?;
let filtered = vt.transform(features)?;
let mut skb = SelectKBest::new(5, Box::new(FClassif::new()));
skb.fit(features.clone(), target)?;
let selected = skb.transform(features)?;
Time Series — Lag Features
use featrs::prelude::*;
let mut lagger = Lagger::new(&["sales", "revenue"], &[1, 7, 30]);
lagger.fit(df.clone())?;
let lagged = lagger.transform(df)?; // adds sales_lag_1, sales_lag_7, ...
Time Series — Rolling Windows
use featrs::prelude::*;
use featrs::time_series::rolling::RollingFn;
let mut rolling = RollingAggregator::new(&["price"], 7, RollingFn::Mean);
rolling.fit(df.clone())?;
let result = rolling.transform(df)?; // adds price_mean_7
Time Series — Differencing
use featrs::prelude::*;
let mut diff = Difference::diff(&["sales"], 1);
diff.fit(df.clone())?;
let result = diff.transform(df)?; // adds sales_diff_1
let mut pct = Difference::pct_change(&["price"], 1);
pct.fit(df.clone())?;
let result = pct.transform(df)?; // adds price_pct_1
Cyclical Encoding
use featrs::prelude::*;
let mut enc = CyclicalEncoder::new(&["hour"], 24);
enc.fit(df.clone())?;
let result = enc.transform(df)?; // adds hour_sin, hour_cos
Feature Hasher
use featrs::prelude::*;
let mut fh = FeatureHasher::new(&["user_id", "category"], 100);
fh.fit(df.clone())?;
let hashed = fh.transform(df)?; // 100 hashed columns
Target encoding (leave-one-out)
use featrs::prelude::*;
use polars::prelude::*;
let x = df!(
"city" => &["paris", "paris", "berlin", "berlin", "berlin"],
"spend" => &[10.0_f64, 20.0, 30.0, 40.0, 50.0]
)?;
let y = df!("revenue" => &[100.0_f64, 120.0, 200.0, 220.0, 240.0])?;
let mut enc = LeaveOneOutEncoder::new().alpha(1.0);
enc.fit(x.clone(), y)?;
// Training rows: each row's category mean excludes its own target; the smoothing prior is the global mean over all training targets.
let encoded = enc.transform(x)?;
// Unseen rows: full-sample category means smoothed with alpha; unseen categories get the global mean.
let new_rows = enc.transform_unseen(df!("city" => &["paris", "tokyo"])?)?;
AutoImputer
use featrs::prelude::*;
let mut imp = AutoImputer::new();
imp.fit(df.clone())?;
// Which strategy each Float64 column got, e.g. "Mean+Median".
println!("{:?}", imp.chosen_name());
let filled = imp.transform(df)?;
Missing Indicator
use featrs::prelude::*;
let mut ind = MissingIndicator::all();
ind.fit(df.clone())?;
let marked = ind.transform(df)?; // adds {col}_missing where nulls exist
Auto-Type Detection
use featrs::prelude::*;
let mut atd = AutoTypeDetector::new()
.cat_threshold(30) // one-hot if < 30 unique values
.hash_buckets(200) // hash to 200 buckets otherwise
.numeric_string_threshold(0.9); // >= 90% numeric-looking -> passthrough
atd.fit(df.clone())?;
let result = atd.transform(df)?;
AutoPipeline
use featrs::prelude::*;
use featrs::traits::{Fit, Transform};
let mut auto = AutoPipeline::new(
AutoPipelineConfig::default()
.target("churned") // held out, never transformed
.imputer(AutoImputerConfig::default()) // fill Float64 nulls
.scaler(AutoScalerConfig::default()) // scale Float64 columns
.cat_threshold(30),
);
auto.fit(df.clone())?;
// Review what was inferred before transforming.
for (name, _) in auto.prepared_pipeline()?.steps() {
println!("{name}");
}
let features = auto.transform(df)?; // the target column is dropped
It drops all-null columns, removes constants, expands datetime components,
one-hot encodes low-cardinality strings, hashes or target-encodes
high-cardinality strings, and freezes the feature schema so transform
rejects drifted inputs.
Data Quality Report
use featrs::prelude::*;
let report = DataQualityReport::from_dataframe(&df)?;
// Per-column findings and frame-level totals.
println!("{} nulls in {} cells", report.overall.total_nulls, report.overall.total_cells);
for r in &report.columns {
println!("{}: {:?} cardinality, {} unique", r.name, r.cardinality, r.unique_count);
}
// Preprocessing suggestions: DropColumn, ImputeColumn, ScaleColumn, EncodeColumn,
// RemoveDuplicates (CleanStrings is reserved for a later revision).
for rec in &report.recommendations {
println!("{rec:?}");
}
report.print_summary(); // to_markdown() written to stdout
let md = report.to_markdown(); // GitHub-friendly tables
Roadmap
Work is tracked in GitHub milestones. Open issues are grouped by release so contributors can pick a target and see what ships with it.
| Milestone | Focus | Target |
|---|---|---|
| v0.4.0 | New transformers: scalers, encoders, cleaners | Released (Aug 2026) |
| v0.4.1 | Correctness fixes for encoders, discretizers, and variance | Released (Sep 2026) |
| v0.5.0 | Text, time-series, feature selection | Released (Oct 2026) |
| v0.6.0 | Pipeline composition & automation (FeatureUnion, AutoPipeline, SchemaValidator) | Nov 2026 |
| v0.7.0 | Performance workstream (benchmarks, Polars-native kernels, rayon, ahash) + LazyFrame & streaming | Dec 2026 |
| v0.8.0 | Quality & docs hardening (lints, doc tests) | Dec 2026 |
| v1.0.0 | Persistence (serde), tracing, ONNX export, pipeline versioning | Mar 2027 |
The performance milestones are ordered: benchmarks (Phase 0) land first, then Polars-native kernels, rayon, and ahash. ahash must stabilize before serde persistence ships so the on-disk hash format never changes.
New contributors: start with a good first issue in the next milestone.
Resources
Star History
License
MIT
استكشف مشاريع مشابهة ومرتبطة
جارٍ التحميل…