PyElasticNet

Struct PyElasticNet 

Source
pub struct PyElasticNet { /* private fields */ }
Expand description

Linear regression with combined L1 and L2 priors as regularizer.

Minimizes the objective function:

1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2

If you are interested in controlling the L1 and L2 penalty separately, keep in mind that this is equivalent to:

a * L1 + b * L2

where:

alpha = a + b and l1_ratio = a / (a + b)

The parameter l1_ratio corresponds to alpha in the glmnet R package while alpha corresponds to the lambda parameter in glmnet. Specifically, l1_ratio = 1 is the lasso penalty. Currently, l1_ratio <= 0.01 is not reliable, unless you supply your own sequence of alpha.

§Parameters

alpha : float, default=1.0 Constant that multiplies the penalty terms. Defaults to 1.0. See the notes for the exact mathematical meaning of this parameter. alpha = 0 is equivalent to an ordinary least square, solved by the :class:LinearRegression object. For numerical reasons, using alpha = 0 with the Lasso object is not advised. Given this, you should use the :class:LinearRegression object.

l1_ratio : float, default=0.5 The ElasticNet mixing parameter, with 0 <= l1_ratio <= 1. For l1_ratio = 0 the penalty is an L2 penalty. For l1_ratio = 1 it is an L1 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.

fit_intercept : bool, default=True Whether to calculate the intercept for this model. If set to False, no intercept will be used in calculations (i.e. data is expected to be centered).

copy_X : bool, default=True If True, X will be copied; else, it may be overwritten.

max_iter : int, default=1000 The maximum number of iterations for the optimization algorithm.

tol : float, default=1e-4 The tolerance for the optimization: if the updates are smaller than tol, the optimization code checks the dual gap for optimality and continues until it is smaller than tol, see Notes below.

warm_start : bool, default=False When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. See :term:the Glossary <warm_start>.

positive : bool, default=False When set to True, forces the coefficients to be positive.

random_state : int, RandomState instance, default=None The seed of the pseudo random number generator that selects a random feature to update. Used when selection == ‘random’. Pass an int for reproducible output across multiple function calls. See :term:Glossary <random_state>.

selection : {‘cyclic’, ‘random’}, default=‘cyclic’ If set to ‘random’, a random coefficient is updated every iteration rather than looping over features sequentially by default. This (setting to ‘random’) often leads to significantly faster convergence especially when tol is higher than 1e-4.

§Attributes

coef_ : ndarray of shape (n_features,) or (n_targets, n_features) Parameter vector (w in the cost function formula).

sparse_coef_ : sparse matrix of shape (n_features,) or
(n_targets, n_features) Sparse representation of the fitted coef_.

intercept_ : float or ndarray of shape (n_targets,) Independent term in decision function.

n_features_in_ : int Number of features seen during :term:fit.

n_iter_ : list of int Number of iterations run by the coordinate descent solver to reach the specified tolerance.

§Examples

from sklears_python import ElasticNet from sklearn.datasets import make_regression X, y = make_regression(n_features=2, random_state=0) regr = ElasticNet(random_state=0) regr.fit(X, y) ElasticNet(random_state=0) print(regr.coef_) [18.83816119 64.55968437] print(regr.intercept_) 1.451… print(regr.predict([[0, 0]])) [1.451…]

§Notes

To avoid unnecessary memory duplication the X argument of the fit method should be directly passed as a Fortran-contiguous NumPy array.

The precise stopping criteria based on tol are the following: First, check that that maximum coordinate update, i.e. :math:\\max_j |w_j^{new} - w_j^{old}| is smaller than tol times the maximum absolute coefficient, :math:\\max_j |w_j|. If so, then additionally check whether the dual gap is smaller than tol times :math:||y||_2^2 / n_\\text{samples}.

Trait Implementations§

Source§

impl<'py> IntoPyObject<'py> for PyElasticNet

Source§

type Target = PyElasticNet

The Python output type
Source§

type Output = Bound<'py, <PyElasticNet as IntoPyObject<'py>>::Target>

The smart pointer type to use. Read more
Source§

type Error = PyErr

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

fn into_pyobject( self, py: Python<'py>, ) -> Result<<Self as IntoPyObject<'_>>::Output, <Self as IntoPyObject<'_>>::Error>

Performs the conversion.
Source§

impl PyClass for PyElasticNet

Source§

type Frozen = False

Whether the pyclass is frozen. Read more
Source§

impl PyClassImpl for PyElasticNet

Source§

const IS_BASETYPE: bool = false

#[pyclass(subclass)]
Source§

const IS_SUBCLASS: bool = false

#[pyclass(extends=…)]
Source§

const IS_MAPPING: bool = false

#[pyclass(mapping)]
Source§

const IS_SEQUENCE: bool = false

#[pyclass(sequence)]
Source§

const IS_IMMUTABLE_TYPE: bool = false

#[pyclass(immutable_type)]
Source§

type BaseType = PyAny

Base class
Source§

type ThreadChecker = SendablePyClass<PyElasticNet>

This handles following two situations: Read more
Source§

type PyClassMutability = <<PyAny as PyClassBaseType>::PyClassMutability as PyClassMutability>::MutableChild

Immutable or mutable
Source§

type Dict = PyClassDummySlot

Specify this class has #[pyclass(dict)] or not.
Source§

type WeakRef = PyClassDummySlot

Specify this class has #[pyclass(weakref)] or not.
Source§

type BaseNativeType = PyAny

The closest native ancestor. This is PyAny by default, and when you declare #[pyclass(extends=PyDict)], it’s PyDict.
Source§

fn items_iter() -> PyClassItemsIter

Source§

fn doc(py: Python<'_>) -> PyResult<&'static CStr>

Rendered class doc
Source§

fn lazy_type_object() -> &'static LazyTypeObject<Self>

Source§

fn dict_offset() -> Option<isize>

Source§

fn weaklist_offset() -> Option<isize>

Source§

impl PyClassNewTextSignature<PyElasticNet> for PyClassImplCollector<PyElasticNet>

Source§

fn new_text_signature(self) -> Option<&'static str>

Source§

impl<'a, 'py> PyFunctionArgument<'a, 'py, false> for &'a PyElasticNet

Source§

type Holder = Option<PyRef<'py, PyElasticNet>>

Source§

fn extract( obj: &'a Bound<'py, PyAny>, holder: &'a mut Self::Holder, ) -> PyResult<Self>

Source§

impl<'a, 'py> PyFunctionArgument<'a, 'py, false> for &'a mut PyElasticNet

Source§

type Holder = Option<PyRefMut<'py, PyElasticNet>>

Source§

fn extract( obj: &'a Bound<'py, PyAny>, holder: &'a mut Self::Holder, ) -> PyResult<Self>

Source§

impl PyMethods<PyElasticNet> for PyClassImplCollector<PyElasticNet>

Source§

fn py_methods(self) -> &'static PyClassItems

Source§

impl PyTypeInfo for PyElasticNet

Source§

const NAME: &'static str = "ElasticNet"

Class name.
Source§

const MODULE: Option<&'static str> = ::core::option::Option::None

Module name, if any.
Source§

fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject

Returns the PyTypeObject instance for this type.
Source§

fn type_object(py: Python<'_>) -> Bound<'_, PyType>

Returns the safe abstraction over the type object.
Source§

fn is_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type or a subclass of this type.
Source§

fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type.
Source§

impl DerefToPyAny for PyElasticNet

Auto Trait Implementations§

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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<'py, T> IntoPyObjectExt<'py> for T
where T: IntoPyObject<'py>,

Source§

fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr>

Converts self into an owned Python object, dropping type information.
Source§

fn into_py_any(self, py: Python<'py>) -> Result<Py<PyAny>, PyErr>

Converts self into an owned Python object, dropping type information and unbinding it from the 'py lifetime.
Source§

fn into_pyobject_or_pyerr(self, py: Python<'py>) -> Result<Self::Output, PyErr>

Converts self into a Python object. 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> PyErrArguments for T
where T: for<'py> IntoPyObject<'py> + Send + Sync,

Source§

fn arguments(self, py: Python<'_>) -> Py<PyAny>

Arguments for exception
Source§

impl<T> PyTypeCheck for T
where T: PyTypeInfo,

Source§

const NAME: &'static str = <T as PyTypeInfo>::NAME

Name of self. This is used in error messages, for example.
Source§

fn type_check(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of Self, which may include a subtype. Read more
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

Source§

impl<T> Ungil for T
where T: Send,