How do you do a regression using your package?

How do I do I simple linear regression using your framework? Your operations are not clear… It fails on taking an inverse and cal of the betas . XtX and XtY are correct.

    let x: Vec<f64> = vec![1.0,1.0,1.0,1.0,1.0,3.0,1.0,5.0,2.0,4.0,5.0,4.0,6.0,4.0,6.0];
    let y: Vec<f64> = vec![3.0,1.0,8.0,3.0,5.0];

    let X = DMatrix::from_iterator(
        5,
        3,
        x
            .iter()
            .cloned(),
    );

    

    let mut Y = DMatrix::from_iterator(
        5,
        1,
        y
            .iter()
            .cloned(),
    );

let XX = &X.transpose()*&X;
let XY = &X.transpose()*&Y;

let XX_inv = &XX.try_inverse();
let beta = &XX_inv*&XY;

error[E0369]: binary operation * cannot be applied to type &std::option::Option<na::Matrix<f64, na::Dynamic, na::Dynamic, na::VecStorage<f64, na::Dynamic, na::Dynamic>>>
–> src/arima_estimation.rs:101:16
|
101 | let beta = XX_inv*XY;
| ^^^^^^^^^
|
= note: an implementation of std::ops::Mul might be missing for &std::option::Option<na::Matrix<f64, na::Dynamic, na::Dynamic, na::VecStorage<f64, na::Dynamic, na::Dynamic>>>

Hi!

The error message you are getting:

error[E0369]: binary operation * cannot be applied to type
&std::option::Option<na::Matrix<f64, na::Dynamic, na::Dynamic, na::VecStorage<f64, na::Dynamic, na::Dynamic>>>

means there is no multiplication defined on an &Option<Matrix<...>> type. This is expected because that would not make sense for the None variant of the Option. What you need to do is to retrieve the value inside of the Option if the inversion succeeded and deal with the case where the inversion failed otherwise:

if let Some(XX_inv) = XX.try_inverse() {
  // Inversion succeeded.
  let beta = &XX_inv * &XY;
} else {
  // Deal with the case where inversion failed.
}

Also, as a side note, note that you can do X.transpose() * &Y (and X.transpose() * &X) more efficiently by using the tr_mul method: X.tr_mul(&Y).

1 Like

Thanks I will try that out. Actually figured out how to use the svd to solve:

let svd = SVD::new(X.clone(), true, true);  //compute u compute v
let betas = svd.solve(&Y,0.0001);
println!("betas {} {} {}",betas[0],betas[1], betas[2]);