diff --git a/CHANGELOG.md b/CHANGELOG.md index 5dc07196..20a6f4ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - `ensemble`: `ExtraTreesRegressor::predict_oob` returns an error when the forest was fitted without bootstrap. Before this change, it returned `NaN` for a float target and panicked for an integer target (#520). - `ensemble`: `RandomForestRegressor::predict_oob` and `ExtraTreesRegressor::predict_oob` return an error when a row is in-bag for all trees. Before this change, it returned `NaN` for a float target and panicked for an integer target. +- `linalg`: `variance` and `std_dev` use a numerically stable formula. Before this change, columns far from zero (for example Unix timestamps) had a variance that was wrong, `0` or negative. This affected `StandardScaler`, `GaussianNB`, `RidgeRegression`, `Lasso` and `ElasticNet`. +- `preprocessing`: `StandardScaler` divides a column with zero variance by `1`, as scikit-learn does. Before this change, the result was `NaN` for a constant `f32` column, and very large for new values in a constant `f64` column. ### Changed - `tree`, `ensemble`: `DecisionTreeClassifier` and `RandomForestClassifier` now use `BaseTree` and `BaseForest`, the same code as the regressors. The new `GiniCriterion`, `EntropyCriterion` and `ClassificationErrorCriterion` implement the `Criterion` trait. The entropy improvement uses a numerically stable formula that is never negative. Exactly tied splits can be broken in a different way, so fitted trees can differ slightly from earlier versions. diff --git a/src/linalg/basic/arrays.rs b/src/linalg/basic/arrays.rs index 11774a5f..57d1f197 100644 --- a/src/linalg/basic/arrays.rs +++ b/src/linalg/basic/arrays.rs @@ -308,16 +308,23 @@ pub trait ArrayView1: Array { { let n = self.shape(); + // Welford's algorithm. The difference of two large sums of squares is not stable. + // The first value is subtracted so that the running mean does not round away + // the spread of values far from zero. + let offset = if n > 0 { + T::to_f64(self.get(0)).unwrap() + } else { + 0f64 + }; let mut mu = 0f64; let mut sum = 0f64; - let div = n as f64; for i in 0..n { - let xi = T::to_f64(self.get(i)).unwrap(); - mu += xi; - sum += xi * xi; + let xi = T::to_f64(self.get(i)).unwrap() - offset; + let delta = xi - mu; + mu += delta / (i + 1) as f64; + sum += delta * (xi - mu); } - mu /= div; - sum / div - mu.powi(2) + sum / n as f64 } /// return variance fn std_dev(&self) -> f64 @@ -485,19 +492,30 @@ pub trait ArrayView2: Array 0 { + match axis { + 0 => T::to_f64(self.get((0, i))).unwrap(), + _ => T::to_f64(self.get((i, 0))).unwrap(), + } + } else { + 0f64 + }; let mut mu = 0f64; let mut sum = 0f64; for j in 0..m { let a = match axis { 0 => T::to_f64(self.get((j, i))).unwrap(), _ => T::to_f64(self.get((i, j))).unwrap(), - }; - mu += a; - sum += a * a; + } - offset; + let delta = a - mu; + mu += delta / (j + 1) as f64; + sum += delta * (a - mu); } - mu /= div; - *x_i = sum / div - mu.powi(2); + *x_i = sum / div; } x @@ -1681,6 +1699,32 @@ mod tests { assert_eq!(vec![1., 2.].std_dev(), 0.5); assert_eq!(vec![1.].variance(), 0.0); assert_eq!(vec![1.].std_dev(), 0.0); + // values far from zero + assert_eq!( + vec![1e9 + 1., 1e9 + 2., 1e9 + 3., 1e9 + 4.].variance(), + 1.25 + ); + assert_eq!(vec![0.1; 10].variance(), 0.0); + // the mean of these two values is not representable + assert_eq!(vec![1e16, 1e16 + 2.].variance(), 1.0); + assert_eq!(vec![1e16 + 2., 1e16].variance(), 1.0); + } + + #[test] + fn test_matrix_variance_far_from_zero() { + let x = DenseMatrix::from_2d_array(&[ + &[1e9 + 1., 0.1], + &[1e9 + 2., 0.1], + &[1e9 + 3., 0.1], + &[1e9 + 4., 0.1], + ]) + .unwrap(); + assert_eq!(x.variance(0), vec![1.25, 0.0]); + assert_eq!(x.transpose().variance(1), vec![1.25, 0.0]); + // the mean of the two values in each column is not representable + let x = DenseMatrix::from_2d_array(&[&[1e16, 1e16 + 2.], &[1e16 + 2., 1e16]]).unwrap(); + assert_eq!(x.variance(0), vec![1.0, 1.0]); + assert_eq!(x.variance(1), vec![1.0, 1.0]); } #[test] diff --git a/src/linear/elastic_net.rs b/src/linear/elastic_net.rs index f1045420..4e3a2e43 100644 --- a/src/linear/elastic_net.rs +++ b/src/linear/elastic_net.rs @@ -629,6 +629,13 @@ mod tests { for normalize in [false, true] { // The existing interior-point solver is unstable at a zero L1 penalty. for ratio in [0.05, 0.5, 1.0] { + // With more columns than rows and no L2 penalty the solver is sensitive + // to the last bit of the column scales: the f64 fits differ by 1.5e-6. + let tolerance = if normalize && p > n && ratio == 1.0 { + tolerance.max(1e-5) + } else { + tolerance + }; let parameters = ElasticNetParameters::default() .with_alpha(0.04) .with_lazy_normalization(lazy_normalization) diff --git a/src/naive_bayes/gaussian.rs b/src/naive_bayes/gaussian.rs index 08fc31d0..f1eb1af8 100644 --- a/src/naive_bayes/gaussian.rs +++ b/src/naive_bayes/gaussian.rs @@ -407,13 +407,12 @@ mod tests { assert_eq!(gnb.class_count(), &[3, 3]); - assert_eq!( - gnb.var(), - &[ - &[0.666666666666667, 0.22222222222222232], - &[0.666666666666667, 0.22222222222222232] - ] - ); + assert_eq!(gnb.var().len(), 2); + for var in gnb.var() { + assert_eq!(var.len(), 2); + assert!((var[0] - 2. / 3.).abs() < 1e-15); + assert!((var[1] - 2. / 9.).abs() < 1e-15); + } assert_eq!(gnb.class_priors(), &[0.5, 0.5]); diff --git a/src/preprocessing/numerical.rs b/src/preprocessing/numerical.rs index 3c37e0c0..28cb5e66 100644 --- a/src/preprocessing/numerical.rs +++ b/src/preprocessing/numerical.rs @@ -108,11 +108,10 @@ impl StandardScaler { } /// Make sure the standard deviation is valid. If it is -/// negative or zero, it should replaced by the smallest -/// positive value the type can have. That way we can savely -/// divide the columns with the resulting scalar. +/// negative or zero, it should be replaced by one. A constant +/// column is then only centered and is never divided by zero. fn ensure_std_valid(value: T) -> T { - value.max(T::min_positive_value()) + if value > T::zero() { value } else { T::one() } } /// During `fit` the `StandardScaler` computes the column means and standard deviation. @@ -175,13 +174,13 @@ mod tests { use super::super::ensure_std_valid; #[test] - fn negative_value_should_be_replace_with_minimal_positive_value() { - assert_eq!(ensure_std_valid(-1.0), f64::MIN_POSITIVE) + fn negative_value_should_be_replaced_with_one() { + assert_eq!(ensure_std_valid(-1.0), 1.0) } #[test] - fn zero_should_be_replace_with_minimal_positive_value() { - assert_eq!(ensure_std_valid(0.0), f64::MIN_POSITIVE) + fn zero_should_be_replaced_with_one() { + assert_eq!(ensure_std_valid(0.0), 1.0) } } mod standard_scaler { @@ -288,6 +287,68 @@ mod tests { ) } + /// A constant `f32` column must not be divided by zero. + #[test] + fn fit_transform_with_zero_variance_f32() { + let x = DenseMatrix::from_2d_array(&[&[1.0f32, 1.0], &[1.0, 3.0]]).unwrap(); + let scaler = StandardScaler::fit(&x, StandardScalerParameters::default()).unwrap(); + assert_eq!( + scaler.transform(&x).unwrap(), + DenseMatrix::from_2d_array(&[&[0.0f32, -1.0], &[0.0, 1.0]]).unwrap() + ); + } + + /// New values in a column that was constant during `fit` are only + /// centered, as in sklearn. + #[test] + fn transform_new_values_in_column_with_zero_variance() { + let x = DenseMatrix::from_2d_array(&[&[1.0], &[1.0]]).unwrap(); + let scaler = StandardScaler::fit(&x, StandardScalerParameters::default()).unwrap(); + assert_eq!( + scaler + .transform(&DenseMatrix::from_2d_array(&[&[1.5], &[3.0]]).unwrap()) + .unwrap(), + DenseMatrix::from_2d_array(&[&[0.5], &[2.0]]).unwrap() + ); + } + + /// The mean of ten times `0.1` is not exactly `0.1`. + #[test] + fn fit_transform_with_zero_variance_and_rounded_mean() { + let x = DenseMatrix::from_2d_array(&[&[0.1][..]; 10]).unwrap(); + assert!( + fit_transform_with_default_standard_scaler(&x).approximate_eq( + &DenseMatrix::from_2d_array(&[&[0.0][..]; 10]).unwrap(), + 1e-15 + ) + ); + } + + /// Columns far from zero, for example Unix timestamps. Expected values + /// taken from sklearn. + #[test] + fn fit_transform_with_large_mean() { + let x = DenseMatrix::from_2d_array(&[ + &[1_700_000_001.0], + &[1_700_000_002.0], + &[1_700_000_003.0], + &[1_700_000_004.0], + ]) + .unwrap(); + assert!( + fit_transform_with_default_standard_scaler(&x).approximate_eq( + &DenseMatrix::from_2d_array(&[ + &[-1.3416407864998738], + &[-0.4472135954999579], + &[0.4472135954999579], + &[1.3416407864998738], + ]) + .unwrap(), + 1e-12 + ) + ); + } + /// Test `fit` for columns with nice summary statistics. #[test] fn fit_for_simple_values() {