Editor

Train a Logistic Regression Model

Advanced · Write the code · from Predict Customer Churn: End-to-End Data Analysis (with sklearn)

From the lesson: Step 5: Train a Classification Model

Now for the exciting part - training the model. Logistic Regression is a great starting point for binary classification. It's fast, interpretable, and works well when features have a roughly linear relationship with the outcome.

Read this part of the lesson

Using the prepared features, train a LogisticRegression model. Then print:

1. "Model trained successfully"

2. The model coefficients with their feature names

3. The training accuracy using model.score(X_scaled, y)

Format accuracy as: Training accuracy: X.XX

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
data = {
'tenure_months': [2, 34, 5, 45, 12, 1, 60, 8, 24, 48,
3, 36, 7, 52, 15, 2, 42, 10, 30, 6],
'monthly_charges': [70, 45, 85, 30, 65, 90, 25, 75, 55, 35,
88, 40, 78, 28, 60, 92, 32, 72, 50, 82],
'contract': ['Month', 'Year', 'Month', 'TwoYear', 'Month', 'Month', 'TwoYear',
'Month', 'Year', 'TwoYear', 'Month', 'Year', 'Month', 'TwoYear',
'Year', 'Month', 'TwoYear', 'Month', 'Year', 'Month'],
'churned': [1, 0, 1, 0, 1, 1, 0, 1, 0, 0,
1, 0, 1, 0, 0, 1, 0, 1, 0, 1]
}
df = pd.DataFrame(data)
df_encoded = pd.get_dummies(df, columns=['contract'], drop_first=True)
feature_cols = ['tenure_months', 'monthly_charges', 'contract_TwoYear', 'contract_Year']
X = df_encoded[feature_cols]
y = df_encoded['churned']
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Train a LogisticRegression model and print results

More Churn Prediction exercises

All Python exercises · 50 practice problems · Practical Projects quiz