Skip to main content

GradientDescent

Struct GradientDescent 

Source
pub struct GradientDescent<L, V, F = f64> { /* private fields */ }
Expand description

Steepest-descent solver: step in the direction of −∇f(x) with a pluggable line search and optional heavy-ball momentum.

The line search type parameter L is the strategy (e.g. Constant, Backtracking, Wolfe). Use GradientDescent::new for a fixed step or GradientDescent::with_line_search to pick a strategy explicitly.

§Momentum

with_momentum adds a heavy-ball velocity term (Polyak 1964). With momentum coefficient β and the per-step length αₖ chosen by the line search, the update becomes

vₖ₊₁ = β · vₖ − αₖ · ∇f(xₖ)
xₖ₊₁ = xₖ + vₖ₊₁

starting from v₀ = 0. β = 0 (the default) is exactly plain steepest descent; β ∈ (0, 1) carries momentum, which cancels the oscillating component of the gradient across a narrow valley while accumulating speed along the valley floor. With a Constant step this is the classical heavy-ball method — well-behaved on the curved, ill-conditioned Rosenbrock valley where plain steepest descent zig-zags. A too-large effective step (roughly α / (1 − β) along consistent directions) diverges, so reduce α when adding momentum.

§Backends

Backend-generic — works with any V implementing ScaledAdd<F> + NegInPlace + ScaleInPlace<F> + Clone. With the default F = f64 that covers Vec<f64>, nalgebra::DVector<f64> (feature nalgebra), ndarray::Array1<f64> (feature ndarray), and faer::Col<f64> (feature faer).

§References

Polyak, B. T. (1964). “Some methods of speeding up the convergence of iteration methods.” USSR Computational Mathematics and Mathematical Physics, 4(5), 1–17. doi:10.1016/0041-5553(64)90137-5.

§Examples

Minimize the 2-D sphere f(x) = x₀² + x₁² from (1, 1):

use basin::{BasicState, CostFunction, Executor, Gradient, GradientDescent, GradientTolerance};

struct Sphere;
impl CostFunction for Sphere {
    type Param = Vec<f64>;
    type Output = f64;
    type Error = std::convert::Infallible;
    fn cost(&self, x: &Vec<f64>) -> Result<f64, Self::Error> {
        Ok(x.iter().map(|xi| xi * xi).sum())
    }
}
impl Gradient for Sphere {
    type Gradient = Vec<f64>;
    fn gradient(&self, x: &Vec<f64>) -> Result<Vec<f64>, Self::Error> {
        Ok(x.iter().map(|xi| 2.0 * xi).collect())
    }
}

let result = Executor::new(Sphere, GradientDescent::new(0.1), BasicState::new(vec![1.0, 1.0]))
    .max_iter(1_000)
    .terminate_on(GradientTolerance(1e-8))
    .run()
    .unwrap();
assert!(result.cost() < 1e-12);

Implementations§

Source§

impl<V, F: Scalar> GradientDescent<Constant<F>, V, F>

Source

pub fn new(alpha: F) -> Self

Gradient descent with a fixed step size alpha. Equivalent to with_line_search(Constant(alpha)).

Source§

impl<L, V, F: Scalar> GradientDescent<L, V, F>

Gradient descent with an explicit line-search strategy (e.g. Backtracking, Wolfe).

Source

pub fn with_momentum(self, beta: F) -> Self

Enable heavy-ball momentum with coefficient beta (Polyak 1964). beta = 0.0 is plain steepest descent; beta in (0, 1) (commonly 0.9) adds momentum. See the type docs for the update rule and stability caveat.

Trait Implementations§

Source§

impl<L, V, F> InitialState<V> for GradientDescent<L, V, F>
where F: Scalar, V: Clone,

Lets GradientDescent serve as the inner of a composed solver (e.g. BarrierMethod / AugmentedLagrangianMethod), seeding a fresh BasicState at the warm-start point.

Source§

type State = BasicState<V, F>

State shape this solver iterates against.
Source§

fn seed(&self, x: &V) -> BasicState<V, F>

Build a fresh state seeded at x using the solver’s natural default scale.
Source§

impl<P, V, F, L> Solver<P, BasicState<V, F>> for GradientDescent<L, V, F>
where F: Scalar, P: CostFunction<Param = V, Output = F> + Gradient<Gradient = V>, V: ScaledAdd<F> + NegInPlace + ScaleInPlace<F> + Clone, L: LineSearch<P, V, F, Error = P::Error>,

Source§

type Error = <P as CostFunction>::Error

Hard-abort error type — mirrors the underlying problem’s type Error. See the trait docs.
Source§

fn init( &mut self, problem: &mut Problem<P>, state: BasicState<V, F>, ) -> Result<BasicState<V, F>, Self::Error>

One-time setup before the iteration loop. Read more
Source§

fn next_iter( &mut self, problem: &mut Problem<P>, state: BasicState<V, F>, ) -> Result<(BasicState<V, F>, Option<TerminationReason>), Self::Error>

Advance one iteration. Read more
Source§

fn terminate(&self, _state: &S) -> Option<TerminationReason>

Optional pre-iteration solver-specific termination test. Read more
Source§

impl<L, V, F> WarmStart<V> for GradientDescent<L, V, F>
where F: Scalar, V: Clone,

Auto Trait Implementations§

§

impl<L, V, F> Freeze for GradientDescent<L, V, F>
where L: Freeze, F: Freeze, V: Freeze,

§

impl<L, V, F> RefUnwindSafe for GradientDescent<L, V, F>

§

impl<L, V, F> Send for GradientDescent<L, V, F>
where L: Send, F: Send, V: Send,

§

impl<L, V, F> Sync for GradientDescent<L, V, F>
where L: Sync, F: Sync, V: Sync,

§

impl<L, V, F> Unpin for GradientDescent<L, V, F>
where L: Unpin, F: Unpin, V: Unpin,

§

impl<L, V, F> UnsafeUnpin for GradientDescent<L, V, F>

§

impl<L, V, F> UnwindSafe for GradientDescent<L, V, F>
where L: UnwindSafe, F: UnwindSafe, V: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ByRef<T> for T

Source§

fn by_ref(&self) -> &T

Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Imply<T> for U
where T: ?Sized, U: ?Sized,

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V