SKLearner Home | About | Contact | Examples

Configure SGDRegressor "random_state" Parameter

The random_state parameter in scikit-learn’s SGDRegressor controls the randomness in the stochastic gradient descent algorithm.

Stochastic Gradient Descent (SGD) is an optimization algorithm used to find the parameters that minimize the loss function. It updates the parameters iteratively using a subset of training examples, introducing randomness in the optimization process.

The random_state parameter allows you to set a seed for the random number generator, ensuring reproducibility of results. By setting a fixed value, you can obtain consistent outcomes across multiple runs.

The default value for random_state is None, which means the random number generator is the RandomState instance used by numpy.random. In practice, integer values are commonly used as seeds.

from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.linear_model import SGDRegressor
from sklearn.metrics import mean_squared_error
import numpy as np

# Generate synthetic 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 different random_state values
random_state_values = [None, 0, 42, 100]
mse_scores = []

for rs in random_state_values:
    sgd = SGDRegressor(random_state=rs)
    sgd.fit(X_train, y_train)
    y_pred = sgd.predict(X_test)
    mse = mean_squared_error(y_test, y_pred)
    mse_scores.append(mse)
    print(f"random_state={rs}, MSE: {mse:.4f}")

# Check variability
print(f"\nVariability in MSE: {np.std(mse_scores):.4f}")

Running the example gives an output like:

random_state=None, MSE: 0.0096
random_state=0, MSE: 0.0095
random_state=42, MSE: 0.0096
random_state=100, MSE: 0.0095

Variability in MSE: 0.0000

The key steps in this example are:

  1. Generate a synthetic regression dataset
  2. Split the data into train and test sets
  3. Train SGDRegressor models with different random_state values
  4. Evaluate the mean squared error of each model on the test set
  5. Compare the variability in results

Some tips and considerations for setting random_state:

Issues to consider:



See Also