(
feature_rows: &[Vec<f64>],
variance_thresh: f64,
)
| 205 | let inv_rank: Vec<f64> = pca_rank.iter().map(|r| 1.0 / *r as f64).collect(); |
| 206 | let weighted = weighted_kendall_tau(feature_importance_mean, &inv_rank); |
| 207 | |
| 208 | Ok(PcaCorrelation { pearson, spearman, kendall, weighted_kendall_rank: weighted }) |
| 209 | } |
| 210 | |
| 211 | pub fn plot_feature_importance( |
| 212 | importance: &BTreeMap<String, ImportanceStats>, |
| 213 | oob_score: f64, |
| 214 | oos_score: f64, |
| 215 | output_path: Option<&str>, |
| 216 | ) -> Result<(), FeatureImportanceError> { |
| 217 | if let Some(path) = output_path { |
| 218 | let mut s = format!("oob_score,{oob_score}\noos_score,{oos_score}\nfeature,mean,std\n"); |
| 219 | for (k, v) in importance { |
| 220 | s.push_str(&format!("{k},{},{}\n", v.mean, v.std)); |
| 221 | } |
| 222 | std::fs::write(path, s).map_err(|e| FeatureImportanceError::WriteOutput(e.to_string()))?; |
| 223 | } |
| 224 | Ok(()) |
| 225 | } |
| 226 | |
| 227 | /// PCA output: `(eigenvalues, eigenvectors, standardized feature rows)`. |
| 228 | type PcaDecomposition = (Vec<f64>, DMatrix<f64>, Vec<Vec<f64>>); |
| 229 | |
| 230 | fn compute_pca( |
| 231 | feature_rows: &[Vec<f64>], |
| 232 | variance_thresh: f64, |
| 233 | ) -> Result<PcaDecomposition, FeatureImportanceError> { |
| 234 | if feature_rows.iter().any(|r| r.len() != feature_rows[0].len()) { |
| 235 | return Err(FeatureImportanceError::RaggedFeatureRows); |
| 236 | } |
| 237 | let x_std = standardize(feature_rows); |
| 238 | let x = to_dmatrix(&x_std); |
| 239 | let dot = x.transpose() * &x; |
| 240 | let eig = SymmetricEigen::new(dot); |
| 241 | |
| 242 | let mut idx: Vec<usize> = (0..eig.eigenvalues.len()).collect(); |
| 243 | idx.sort_by(|&a, &b| { |
| 244 | eig.eigenvalues[b].partial_cmp(&eig.eigenvalues[a]).unwrap_or(std::cmp::Ordering::Equal) |
| 245 | }); |
| 246 | let mut eval = Vec::with_capacity(idx.len()); |
| 247 | let mut evec_cols = Vec::with_capacity(idx.len()); |
| 248 | for i in idx { |
| 249 | eval.push(eig.eigenvalues[i]); |
no test coverage detected