Skip to content

Commit 6e81d2e

Browse files
committed
Follow up on suggestions by (automated) review.
- Removed all is_none and replaced by match. - Added missing tests - Fixed typo - Fixed lint issue
1 parent 2d24598 commit 6e81d2e

10 files changed

Lines changed: 208 additions & 157 deletions

‎src/ensemble/random_forest_classifier.rs‎

Lines changed: 41 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -554,35 +554,40 @@ impl<TX: FloatNumber + PartialOrd, TY: Number + Ord, X: Array2<TX>, Y: Array1<TY
554554
"'fit' should be called before calling 'predict'",
555555
));
556556
}
557-
let (n, _) = x.shape();
558-
559-
let samples = match &self.samples {
560-
Some(s) => s,
561-
None => {
562-
return Err(Failed::because(
563-
FailedError::PredictFailed,
564-
"Need samples=true for OOB predictions.",
565-
));
566-
}
567-
};
568557

569-
if samples[0].len() != n {
570-
return Err(Failed::because(
571-
FailedError::PredictFailed,
572-
"Prediction matrix must match matrix used in training for OOB predictions.",
573-
));
574-
}
558+
match &self.classes {
559+
Some(classes) => {
560+
let (n, _) = x.shape();
575561

576-
let mut result = Y::zeros(n);
562+
let samples = match &self.samples {
563+
Some(s) => s,
564+
None => {
565+
return Err(Failed::because(
566+
FailedError::PredictFailed,
567+
"Need samples=true for OOB predictions.",
568+
));
569+
}
570+
};
571+
572+
if samples[0].len() != n {
573+
return Err(Failed::because(
574+
FailedError::PredictFailed,
575+
"Prediction matrix must match matrix used in training for OOB predictions.",
576+
));
577+
}
577578

578-
for i in 0..n {
579-
result.set(
580-
i,
581-
self.classes.as_ref().unwrap()[self.predict_for_row_oob(x, i)],
582-
);
583-
}
579+
let mut result = Y::zeros(n);
584580

585-
Ok(result)
581+
for i in 0..n {
582+
result.set(i, classes[self.predict_for_row_oob(x, i)]);
583+
}
584+
585+
Ok(result)
586+
}
587+
None => Err(Failed::predict(
588+
"'fit' should be called before calling 'predict'",
589+
)),
590+
}
586591
}
587592

588593
fn predict_for_row_oob(&self, x: &X, row: usize) -> usize {
@@ -885,6 +890,17 @@ mod tests {
885890
assert_eq!(yhat.err(), Some(Failed::predict(msg)));
886891
}
887892

893+
#[test]
894+
fn predict_oob_without_fit_should_not_panic() {
895+
let tree: RandomForestClassifier<f64, u32, DenseMatrix<f64>, Vec<u32>> =
896+
RandomForestClassifier::new();
897+
let x = DenseMatrix::from_2d_array(&[&[1.0f64]]).expect("Construction of x should work");
898+
let yhat = tree.predict_oob(&x);
899+
assert!(yhat.is_err());
900+
let msg = "'fit' should be called before calling 'predict'";
901+
assert_eq!(yhat.err(), Some(Failed::predict(msg)));
902+
}
903+
888904
#[cfg_attr(
889905
all(target_arch = "wasm32", not(target_os = "wasi")),
890906
wasm_bindgen_test::wasm_bindgen_test

‎src/linear/elastic_net.rs‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -395,19 +395,21 @@ impl<TX: FloatNumber + RealNumber, TY: Number, X: Array2<TX>, Y: Array1<TY>>
395395
/// Predict target values from `x`
396396
/// * `x` - _KxM_ data where _K_ is number of observations and _M_ is number of features.
397397
pub fn predict(&self, x: &X) -> Result<Y, Failed> {
398-
if self.coefficients.is_none() {
399-
return Err(Failed::predict(
398+
match (&self.coefficients, &self.intercept) {
399+
(Some(coefficients), Some(intercept)) => {
400+
let (nrows, _) = x.shape();
401+
let mut y_hat = x.matmul(coefficients);
402+
let bias = X::fill(nrows, 1, *intercept);
403+
y_hat.add_mut(&bias);
404+
Ok(Y::from_iterator(
405+
y_hat.iterator(0).map(|&v| TY::from(v).unwrap()),
406+
nrows,
407+
))
408+
}
409+
(_, _) => Err(Failed::predict(
400410
"'fit' should be called before calling 'predict'",
401-
));
411+
)),
402412
}
403-
let (nrows, _) = x.shape();
404-
let mut y_hat = x.matmul(self.coefficients.as_ref().unwrap());
405-
let bias = X::fill(nrows, 1, self.intercept.unwrap());
406-
y_hat.add_mut(&bias);
407-
Ok(Y::from_iterator(
408-
y_hat.iterator(0).map(|&v| TY::from(v).unwrap()),
409-
nrows,
410-
))
411413
}
412414

413415
/// Get estimates regression coefficients

‎src/linear/lasso.rs‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -367,14 +367,22 @@ impl<TX: FloatNumber + RealNumber, TY: Number, X: Array2<TX>, Y: Array1<TY>> Las
367367
"'fit' should be called before calling 'predict'",
368368
));
369369
}
370-
let (nrows, _) = x.shape();
371-
let mut y_hat = x.matmul(self.coefficients());
372-
let bias = X::fill(nrows, 1, self.intercept.unwrap());
373-
y_hat.add_mut(&bias);
374-
Ok(Y::from_iterator(
375-
y_hat.iterator(0).map(|&v| TY::from(v).unwrap()),
376-
nrows,
377-
))
370+
371+
match (&self.coefficients, &self.intercept) {
372+
(Some(coefficients), Some(intercept)) => {
373+
let (nrows, _) = x.shape();
374+
let mut y_hat = x.matmul(coefficients);
375+
let bias = X::fill(nrows, 1, *intercept);
376+
y_hat.add_mut(&bias);
377+
Ok(Y::from_iterator(
378+
y_hat.iterator(0).map(|&v| TY::from(v).unwrap()),
379+
nrows,
380+
))
381+
}
382+
(_, _) => Err(Failed::predict(
383+
"'fit' should be called before calling 'predict'",
384+
)),
385+
}
378386
}
379387

380388
/// Get estimates regression coefficients

‎src/linear/linear_regression.rs‎

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -335,28 +335,29 @@ impl<
335335
/// Predict target values from `x`
336336
/// * `x` - _KxM_ data where _K_ is number of observations and _M_ is number of features.
337337
pub fn predict_matrix(&self, x: &X) -> Result<X, Failed> {
338-
if self.coefficients.is_none() {
339-
return Err(Failed::predict(
340-
"'fit' should be called before calling 'predict'",
341-
));
342-
}
343-
let (nrows, _) = x.shape();
338+
match (&self.coefficients, &self.intercept) {
339+
(Some(coefficients), Some(intercept)) => {
340+
let (nrows, _) = x.shape();
344341

345-
let intercept = self.intercept_matrix();
346-
let (_, num_targets) = intercept.shape();
342+
let (_, num_targets) = intercept.shape();
347343

348-
let mut y_hat = x.matmul(self.coefficients());
344+
let mut y_hat = x.matmul(coefficients);
349345

350-
// Tile the 1xK intercept across all rows, then add in one pass
351-
let bias = X::from_iterator(
352-
(0..nrows).flat_map(|_| intercept.iterator(0).copied()),
353-
nrows,
354-
num_targets,
355-
0,
356-
);
357-
y_hat.add_mut(&bias);
346+
// Tile the 1xK intercept across all rows, then add in one pass
347+
let bias = X::from_iterator(
348+
(0..nrows).flat_map(|_| intercept.iterator(0).copied()),
349+
nrows,
350+
num_targets,
351+
0,
352+
);
353+
y_hat.add_mut(&bias);
358354

359-
Ok(y_hat)
355+
Ok(y_hat)
356+
}
357+
(_, _) => Err(Failed::predict(
358+
"'fit' should be called before calling 'predict'",
359+
)),
360+
}
360361
}
361362

362363
/// Get estimates regression coefficients
@@ -741,6 +742,7 @@ mod tests {
741742
let msg = "'fit' should be called before calling 'predict'";
742743
assert_eq!(yhat.err(), Some(Failed::predict(msg)));
743744
}
745+
744746
#[test]
745747
fn predict_matrix_without_fit_should_not_panic() {
746748
let model: LinearRegression<f64, f64, DenseMatrix<f64>, Vec<f64>> = LinearRegression::new();

‎src/linear/logistic_regression.rs‎

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -503,37 +503,39 @@ impl<TX: Number + FloatNumber + RealNumber, TY: Number + Ord, X: Array2<TX>, Y:
503503
/// Predict class labels for samples in `x`.
504504
/// * `x` - _KxM_ data where _K_ is number of observations and _M_ is number of features.
505505
pub fn predict(&self, x: &X) -> Result<Y, Failed> {
506-
if self.coefficients.is_none() {
507-
return Err(Failed::predict(
508-
"'fit' should be called before calling 'predict'",
509-
));
510-
}
511-
let n = x.shape().0;
512-
let mut result = Y::zeros(n);
513-
if self.num_classes == 2 {
514-
let y_hat = x.ab(false, self.coefficients(), true);
515-
let intercept = *self.intercept().get((0, 0));
516-
for (i, y_hat_i) in y_hat.iterator(0).enumerate().take(n) {
517-
result.set(
518-
i,
519-
self.classes()[usize::from(
520-
RealNumber::sigmoid(*y_hat_i + intercept) > RealNumber::half(),
521-
)],
522-
);
523-
}
524-
} else {
525-
let mut y_hat = x.matmul(&self.coefficients().transpose());
526-
for r in 0..n {
527-
for c in 0..self.num_classes {
528-
y_hat.set((r, c), *y_hat.get((r, c)) + *self.intercept().get((c, 0)));
506+
match (&self.coefficients, &self.intercept, &self.classes) {
507+
(Some(coefficients), Some(intercept), Some(classes)) => {
508+
let n = x.shape().0;
509+
let mut result = Y::zeros(n);
510+
if self.num_classes == 2 {
511+
let y_hat = x.ab(false, coefficients, true);
512+
let intercept = *intercept.get((0, 0));
513+
for (i, y_hat_i) in y_hat.iterator(0).enumerate().take(n) {
514+
result.set(
515+
i,
516+
classes[usize::from(
517+
RealNumber::sigmoid(*y_hat_i + intercept) > RealNumber::half(),
518+
)],
519+
);
520+
}
521+
} else {
522+
let mut y_hat = x.matmul(&coefficients.transpose());
523+
for r in 0..n {
524+
for c in 0..self.num_classes {
525+
y_hat.set((r, c), *y_hat.get((r, c)) + *intercept.get((c, 0)));
526+
}
527+
}
528+
let class_idxs = y_hat.argmax(1);
529+
for (i, class_i) in class_idxs.iter().enumerate().take(n) {
530+
result.set(i, classes[*class_i]);
531+
}
529532
}
533+
Ok(result)
530534
}
531-
let class_idxs = y_hat.argmax(1);
532-
for (i, class_i) in class_idxs.iter().enumerate().take(n) {
533-
result.set(i, self.classes()[*class_i]);
534-
}
535+
(_, _, _) => Err(Failed::predict(
536+
"'fit' should be called before calling 'predict'",
537+
)),
535538
}
536-
Ok(result)
537539
}
538540

539541
/// Get estimates regression coefficients, this create a sharable reference

‎src/linear/ridge_regression.rs‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -393,18 +393,20 @@ impl<
393393
/// Predict target values from `x`
394394
/// * `x` - _KxM_ data where _K_ is number of observations and _M_ is number of features.
395395
pub fn predict(&self, x: &X) -> Result<Y, Failed> {
396-
if self.coefficients.is_none() {
397-
return Err(Failed::predict(
396+
match (&self.coefficients, &self.intercept) {
397+
(Some(coefficients), Some(intercept)) => {
398+
let (nrows, _) = x.shape();
399+
let mut y_hat = x.matmul(coefficients);
400+
y_hat.add_mut(&X::fill(nrows, 1, *intercept));
401+
Ok(Y::from_iterator(
402+
y_hat.iterator(0).map(|&v| TY::from(v).unwrap()),
403+
nrows,
404+
))
405+
}
406+
(_, _) => Err(Failed::predict(
398407
"'fit' should be called before calling 'predict'",
399-
));
408+
)),
400409
}
401-
let (nrows, _) = x.shape();
402-
let mut y_hat = x.matmul(self.coefficients());
403-
y_hat.add_mut(&X::fill(nrows, 1, self.intercept.unwrap()));
404-
Ok(Y::from_iterator(
405-
y_hat.iterator(0).map(|&v| TY::from(v).unwrap()),
406-
nrows,
407-
))
408410
}
409411

410412
/// Get estimates regression coefficients

‎src/neighbors/knn_classifier.rs‎

Lines changed: 31 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -265,22 +265,24 @@ impl<TX: Number, TY: Number + Ord, X: Array2<TX>, Y: Array1<TY>, D: Distance<Vec
265265
///
266266
/// Returns a vector of size N with class estimates.
267267
pub fn predict(&self, x: &X) -> Result<Y, Failed> {
268-
if self.knn_algorithm.is_none() {
269-
return Err(Failed::predict(
268+
match &self.knn_algorithm {
269+
Some(_) => {
270+
let mut result = Y::zeros(x.shape().0);
271+
272+
let mut row_vec = vec![TX::zero(); x.shape().1];
273+
for (i, row) in x.row_iter().enumerate() {
274+
row.iterator(0)
275+
.zip(row_vec.iter_mut())
276+
.for_each(|(&s, v)| *v = s);
277+
result.set(i, self.classes()[self.predict_for_row(&row_vec)?]);
278+
}
279+
280+
Ok(result)
281+
}
282+
None => Err(Failed::predict(
270283
"'fit' should be called before calling 'predict'",
271-
));
272-
}
273-
let mut result = Y::zeros(x.shape().0);
274-
275-
let mut row_vec = vec![TX::zero(); x.shape().1];
276-
for (i, row) in x.row_iter().enumerate() {
277-
row.iterator(0)
278-
.zip(row_vec.iter_mut())
279-
.for_each(|(&s, v)| *v = s);
280-
result.set(i, self.classes()[self.predict_for_row(&row_vec)?]);
284+
)),
281285
}
282-
283-
Ok(result)
284286
}
285287

286288
/// Compute class probabilities for a single row. All the rest functions will use it
@@ -339,21 +341,23 @@ impl<TX: Number, TY: Number + Ord, X: Array2<TX>, Y: Array1<TY>, D: Distance<Vec
339341
/// Returns a vector of probability vectors, one per sample.
340342
/// Each probability vector has length equal to number of classes and sums to 1.
341343
pub fn predict_proba(&self, x: &X) -> Result<Vec<Vec<f64>>, Failed> {
342-
if self.knn_algorithm.is_none() {
343-
return Err(Failed::predict(
344+
match &self.knn_algorithm {
345+
Some(_) => {
346+
let mut result = Vec::with_capacity(x.shape().0);
347+
let mut row_vec = vec![TX::zero(); x.shape().1];
348+
for row in x.row_iter() {
349+
row.iterator(0)
350+
.zip(row_vec.iter_mut())
351+
.for_each(|(&s, v)| *v = s);
352+
result.push(self.predict_proba_for_row(&row_vec)?);
353+
}
354+
355+
Ok(result)
356+
}
357+
None => Err(Failed::predict(
344358
"'fit' should be called before calling 'predict'",
345-
));
346-
}
347-
let mut result = Vec::with_capacity(x.shape().0);
348-
let mut row_vec = vec![TX::zero(); x.shape().1];
349-
for row in x.row_iter() {
350-
row.iterator(0)
351-
.zip(row_vec.iter_mut())
352-
.for_each(|(&s, v)| *v = s);
353-
result.push(self.predict_proba_for_row(&row_vec)?);
359+
)),
354360
}
355-
356-
Ok(result)
357361
}
358362
}
359363

0 commit comments

Comments
 (0)