SKLearner Home | About | Contact | Examples

Configure ElasticNet "positive" Parameter

The positive parameter in scikit-learn’s ElasticNet enforces non-negative coefficients in the linear model.

ElasticNet is a linear regression model that combines L1 and L2 regularization, making it useful for datasets with correlated features and when feature selection is required. The positive parameter ensures that the coefficients of the linear model are non-negative, which can be beneficial in certain domains where negative values are not meaningful.

By default, the positive parameter is set to False. Setting it to True forces the coefficients to be non-negative.

from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.linear_model import ElasticNet
from sklearn.metrics import mean_squared_error

# Generate synthetic regression dataset
X, y = make_regression(n_samples=1000, n_features=10, noise=0.1, random_state=42)

# Split into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train with positive=False and positive=True
positive_values = [False, True]
results = []

for positive in positive_values:
    en = ElasticNet(positive=positive, random_state=42)
    en.fit(X_train, y_train)
    y_pred = en.predict(X_test)
    mse = mean_squared_error(y_test, y_pred)
    results.append((positive, mse, en.coef_))
    print(f"positive={positive}, MSE: {mse:.3f}")

# Print coefficients for inspection
for positive, mse, coef in results:
    print(f"positive={positive}, Coefficients: {coef}")

Running the example gives an output like:

positive=False, MSE: 2090.250
positive=True, MSE: 2090.250
positive=False, Coefficients: [20.26102659 20.00997733 19.66366733 50.39140906  4.95712741  7.72544175
 47.80870788  6.94868406  2.74733837 39.39354003]
positive=True, Coefficients: [20.26102659 20.00997733 19.66366733 50.39140906  4.95712741  7.72544175
 47.80870788  6.94868406  2.74733837 39.39354003]

The key steps in this example are:

  1. Generate a synthetic regression dataset with positive and negative feature values.
  2. Split the data into training and test sets.
  3. Train ElasticNet models with positive=True and positive=False.
  4. Evaluate the mean squared error (MSE) of each model on the test set.
  5. Compare the coefficient values to understand the impact of the positive parameter.

Some tips and heuristics for setting positive:

Issues to consider:



See Also