SKLearner Home | About | Contact | Examples

Get LogisticRegression "n_iter_" Attribute

Logistic Regression is a linear model used for binary classification tasks. It models the probability that a given input point belongs to a certain class.

The n_iter_ attribute of a fitted LogisticRegression model indicates the number of iterations the solver actually took to converge. This information is useful for tuning the solver parameters and diagnosing convergence issues, especially in cases where the model may not converge within the specified maximum number of iterations.

from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

# Generate a synthetic binary classification dataset
X, y = make_classification(n_samples=1000, n_features=20, n_informative=2, n_redundant=10, random_state=42)

# Split the data 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)

# Initialize a LogisticRegression model with a specific solver and maximum iterations
log_reg = LogisticRegression(solver='lbfgs', max_iter=100, random_state=42)

# Fit the model on the training data
log_reg.fit(X_train, y_train)

# Access the n_iter_ attribute and print its value
print(f"Number of iterations taken by the solver to converge: {log_reg.n_iter_[0]}")

Running the example gives an output like:

Number of iterations taken by the solver to converge: 9

The key steps in this example are:

  1. Generate a synthetic binary classification dataset using make_classification and split it into train and test sets.
  2. Initialize a LogisticRegression model with specific solver settings and a maximum number of iterations.
  3. Fit the model on the training data.
  4. Access the n_iter_ attribute to retrieve the number of iterations taken by the solver to converge and print the result.


See Also