use ndarray::{Array2, ArrayView2};
use solow_core::{Error, Result};
fn monomials(d: usize, degree: usize, include_bias: bool, interaction_only: bool) -> Vec<Vec<u32>> {
let mut out: Vec<Vec<u32>> = Vec::new();
for total in 0..=degree {
if total == 0 {
if include_bias {
out.push(vec![0u32; d]);
}
continue;
}
let mut current = vec![0u32; d];
enumerate(d, total as u32, 0, &mut current, &mut out, interaction_only);
}
out
}
fn enumerate(
d: usize,
remaining: u32,
idx: usize,
current: &mut Vec<u32>,
out: &mut Vec<Vec<u32>>,
interaction_only: bool,
) {
if idx == d - 1 {
current[idx] = remaining;
if !interaction_only || current.iter().all(|&e| e <= 1) {
out.push(current.clone());
}
current[idx] = 0;
return;
}
let cap = if interaction_only { 1 } else { remaining };
for k in (0..=cap.min(remaining)).rev() {
current[idx] = k;
enumerate(d, remaining - k, idx + 1, current, out, interaction_only);
}
current[idx] = 0;
}
#[derive(Clone, Debug, PartialEq)]
pub struct PolynomialFeatures {
pub degree: usize,
pub interaction_only: bool,
pub include_bias: bool,
exponents: Option<Vec<Vec<u32>>>,
}
impl PolynomialFeatures {
pub fn new(degree: usize) -> Self {
Self {
degree,
interaction_only: false,
include_bias: true,
exponents: None,
}
}
pub fn interaction_only(mut self, flag: bool) -> Self {
self.interaction_only = flag;
self
}
pub fn include_bias(mut self, flag: bool) -> Self {
self.include_bias = flag;
self
}
pub fn fit(&mut self, x: ArrayView2<'_, f64>) -> Result<()> {
if x.ncols() == 0 {
return Err(Error::Value(
"PolynomialFeatures::fit: x must have at least one column".into(),
));
}
self.exponents = Some(monomials(
x.ncols(),
self.degree,
self.include_bias,
self.interaction_only,
));
Ok(())
}
pub fn output_columns(&self, d: usize) -> usize {
monomials(d, self.degree, self.include_bias, self.interaction_only).len()
}
pub fn transform(&self, x: ArrayView2<'_, f64>) -> Result<Array2<f64>> {
let d = x.ncols();
let exps = monomials(d, self.degree, self.include_bias, self.interaction_only);
let m = exps.len();
let mut out = Array2::<f64>::zeros((x.nrows(), m));
for i in 0..x.nrows() {
for (k, exp) in exps.iter().enumerate() {
let mut acc = 1.0_f64;
for j in 0..d {
let e = exp[j];
if e == 0 {
continue;
}
let v = x[[i, j]];
let mut p = 1.0;
for _ in 0..e {
p *= v;
}
acc *= p;
}
out[[i, k]] = acc;
}
}
Ok(out)
}
pub fn fit_transform(&self, x: ArrayView2<'_, f64>) -> Result<Array2<f64>> {
let mut clone = self.clone();
clone.fit(x)?;
clone.transform(x)
}
pub fn exponents(&self) -> Option<&[Vec<u32>]> {
self.exponents.as_deref()
}
pub fn exponents_for(&self, d: usize) -> Vec<Vec<u32>> {
monomials(d, self.degree, self.include_bias, self.interaction_only)
}
}
#[cfg(test)]
mod tests {
use super::*;
use approx::assert_abs_diff_eq;
use ndarray::array;
#[test]
fn degree_2_matches_hand_derivation() {
let x = array![[2.0, 3.0]];
let poly = PolynomialFeatures::new(2).include_bias(true);
let out = poly.fit_transform(x.view()).unwrap();
assert_eq!(out.dim(), (1, 6));
assert_abs_diff_eq!(out[[0, 0]], 1.0, epsilon = 1e-12);
assert_abs_diff_eq!(out[[0, 1]], 2.0, epsilon = 1e-12);
assert_abs_diff_eq!(out[[0, 2]], 3.0, epsilon = 1e-12);
assert_abs_diff_eq!(out[[0, 3]], 4.0, epsilon = 1e-12);
assert_abs_diff_eq!(out[[0, 4]], 6.0, epsilon = 1e-12);
assert_abs_diff_eq!(out[[0, 5]], 9.0, epsilon = 1e-12);
}
#[test]
fn interaction_only_drops_pure_powers() {
let x = array![[2.0, 3.0, 5.0]];
let poly = PolynomialFeatures::new(2)
.include_bias(false)
.interaction_only(true);
let out = poly.fit_transform(x.view()).unwrap();
assert_eq!(out.dim(), (1, 6));
assert_abs_diff_eq!(out[[0, 3]], 6.0, epsilon = 1e-12); assert_abs_diff_eq!(out[[0, 4]], 10.0, epsilon = 1e-12); assert_abs_diff_eq!(out[[0, 5]], 15.0, epsilon = 1e-12); }
#[test]
fn column_count_matches_binomial_identity() {
for d in 1..6 {
for degree in 0..5 {
let full = PolynomialFeatures::new(degree)
.include_bias(true)
.output_columns(d);
let expected: usize = (1..=degree).fold(1usize, |acc, k| acc * (d + k) / k);
assert_eq!(full, expected, "d = {d}, p = {degree}");
}
}
}
}