Expand description
Weighted least squares optimization
This module provides weighted least squares methods where each residual can have a different weight, allowing for handling heteroscedastic data (data with varying variance).
§Example
use scirs2_core::ndarray::{array, Array1, Array2};
use scirs2_optimize::least_squares::weighted::{weighted_least_squares, WeightedOptions};
// Define a function that returns the residuals
fn residual(x: &[f64], data: &[f64]) -> Array1<f64> {
let n = data.len() / 2;
let t_values = &data[0..n];
let y_values = &data[n..];
let mut res = Array1::zeros(n);
for i in 0..n {
res[i] = y_values[i] - (x[0] + x[1] * t_values[i]);
}
res
}
// Define the Jacobian
fn jacobian(x: &[f64], data: &[f64]) -> Array2<f64> {
let n = data.len() / 2;
let t_values = &data[0..n];
let mut jac = Array2::zeros((n, 2));
for i in 0..n {
jac[[i, 0]] = -1.0;
jac[[i, 1]] = -t_values[i];
}
jac
}
// Create data
let data = array![0.0, 1.0, 2.0, 3.0, 4.0, 0.1, 0.9, 2.1, 2.9, 4.1];
// Define weights (higher weight = more importance)
let weights = array![1.0, 1.0, 1.0, 10.0, 10.0]; // Last two points have more weight
// Initial guess
let x0 = array![0.0, 0.0];
// Solve using weighted least squares
let result = weighted_least_squares(
residual,
&x0,
&weights,
Some(jacobian),
&data,
None
)?;
assert!(result.success);Structs§
- Weighted
Options - Options for weighted least squares optimization
Functions§
- weighted_
least_ squares - Solve a weighted least squares problem