Week 5 · Logistic regression in sklearn
Read the words of the video
- Imagine trying to guess if a flower is red or blue. Logistic regression helps by giving you a number between 0 and 1. A number like 0.9 means "almost certainly red", while 0.1 means "almost certainly blue". It tells you how likely something is to belong to a specific group.
- First, it calculates a simple "score" for the flower, like summing up points for its petal length and width. Then, it uses a special S-shaped curve, called a sigmoid. This curve transforms the score into a probability, so big scores become high chances, and small scores become low chances.
- Let's try an example. If a flower has petal length 4 and width 2, we first calculate its score. Using our model's recipe, this score turns out to be 0.6. Then, using our S-shaped curve, this 0.6 score becomes a probability of about 0.65. So, it's about 65% likely to be class 1.
- Remember to know your methods: predict_proba gives you percentages, and decision_function gives the raw score. Also, lowering 'C' makes your model simpler and less likely to overfit. Keep practicing how scores become probabilities. You've got this, great job learning logistic regression!
The one-minute story
Despite the name, logistic regression is a classifier. It answers "how likely is it that this flower is class 1?" with a number between 0 and 1.
It works in two small steps. First it computes a score for the example, exactly as a linear model would: a weighted sum of the features plus a bias. Then it squeezes that score through an S-shaped curve (the sigmoid) so that big positive scores turn into "almost certainly yes", big negative scores into "almost certainly no", and a score of exactly 0 into "50/50".
Everything else in this week (probabilities, thresholds, C, three classes) is just how scikit-learn lets you read and tune those two steps.
By the end of this week you can:
- train
LogisticRegressionand readcoef_,intercept_,classes_; - tell
predict,predict_probaanddecision_functionapart and convert between them; - explain the role of
Cand the default settings; - handle more than two classes with softmax regression;
- use
SGDClassifier(loss="log_loss")for the incremental version.
Words you need
- Class / label - the category being predicted.
- Score / logit / decision function - the raw number .
- Probability - , between 0 and 1.
- Decision threshold - the probability above which we say "class 1" (default 0.5).
C- inverse regularisation strength (smallC= strong regularisation).- Softmax regression - the multi-class version of logistic regression.
- Log loss / cross-entropy - the training loss.
Idea 1: From score to probability
For one example :
- . The decision boundary is the straight line (plane) .
- predict class 1.
- Training minimises the log loss (plus a penalty), which is convex; gradient descent (the
lbfgssolver by default) finds the best weights.
Idea 2: Training and reading the model
We take the iris flower data, keep only two species (setosa and versicolor ) and two features (petal length and width):
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
mask = y < 2
X2, y2 = X[mask][:, 2:], y[mask] # petal length, petal width
clf = LogisticRegression().fit(X2, y2)
clf.coef_, clf.intercept_, clf.classes_
coef_ [[2.583 1.069]] # one row of weights: shape (1, 2) for a binary problem
intercept_ [-7.808]
classes_ [0 1]
So . The boundary is : with petal width 1, that is petal length .
Three methods give three views of the same thing, for the example :
x = [[3.0, 1.0]]
clf.decision_function(x) # [1.009] the score z
clf.predict_proba(x) # [[0.2672 0.7328]] P(class 0), P(class 1)
clf.predict(x) # [1] the class (threshold 0.5)
Check by hand: ✓, and ✓ (the second column of predict_proba).
| Method | Returns | Shape for examples, 2 classes |
|---|---|---|
decision_function(X) | the score (a real number) | |
predict_proba(X) | one probability per class; each row sums to 1 | |
predict(X) | the predicted class label | |
score(X, y) | accuracy | a single number |
On this easy data the accuracy is 1.0 and the average log loss is .
A different threshold? predict always uses 0.5. To use another cut-off, take the probabilities yourself: (clf.predict_proba(X)[:, 1] > 0.3).astype(int). This matters for precision/recall in week 6.
Idea 3: The knobs: C, penalty, solver
LogisticRegression(penalty="l2", C=1.0, solver="lbfgs", max_iter=100) # classic defaults
C(default 1.0) is the inverse of the regularisation strength. SmallC= strong regularisation (weights shrink, simpler boundary); largeC= weak regularisation. On the iris data, the total size of the weights is 0.62 forC=0.01and 8.85 forC=100.penalty:'l2'by default (shrinks all weights),'l1'(sparse weights; needs a solver such asliblinearorsaga). In the newest scikit-learn versions this argument is being replaced byl1_ratio; the idea is unchanged.solver:lbfgs(default),liblinear,newton-cg,sag,saga. Different solvers support different penalties and sizes of data.max_iter(default 100): raise it if you see aConvergenceWarning(and scale your features, which helps convergence a lot).- If the classes are perfectly separable, without regularisation the weights would grow without limit; the default
C=1prevents that.
Idea 4: More than two classes
For classes the model has one weight vector per class and uses softmax (MLT week 12):
On all three iris species with the two petal features:
softmax_reg = LogisticRegression(C=30, max_iter=1000).fit(X[:, 2:], y)
softmax_reg.coef_.shape # (3, 2): one row per class
softmax_reg.predict_proba([[5.0, 2.0]]) # [[0. 0.029 0.971]]
softmax_reg.predict([[5.0, 2.0]]) # [2] (virginica)
The three probabilities add to 1, and the prediction is the class with the largest one. (Older scikit-learn versions used multi_class="multinomial" for this; recent ones do it automatically with lbfgs.) coef_ has shape (n_classes, n_features) here but (1, n_features) in the binary case.
Idea 5: The incremental version
from sklearn.linear_model import SGDClassifier
SGDClassifier(loss="log_loss") # logistic regression trained by SGD; has partial_fit
The default loss of SGDClassifier is 'hinge', which gives a linear SVM, not logistic regression. To get logistic regression you must set loss="log_loss". With the SGD version you also get partial_fit for data that arrives in chunks (week 3).
Solved examples
Question. A trained model has coef_ = [[1.5, -2.0]] and intercept_ = [0.5]. For find decision_function, predict_proba and predict.
Solution.
- .
- , so .
predict_proba(columns in the order ofclasses_). - , so
predict.
Question. A 4-class problem has 6 features. What is the shape of coef_, intercept_, and of predict_proba for 10 test examples?
Solution. coef_: . intercept_: . predict_proba(X_test): , and each row sums to 1.
CQuestion. You raise C from 0.01 to 100. What happens to the training accuracy, the size of the weights and the risk of overfitting?
Solution. Weaker regularisation: the weights grow, the training accuracy usually rises (the boundary fits the training data more tightly), and the overfitting risk goes up.
Your turn
coef_=[[0.8, 0.2]], intercept_=[-3]. Give the class-1 probability for .
Need a hint?
Compute first.
Show the full solution
. .
Which call returns an array of probabilities that sums to 1 in each row: predict, predict_proba, decision_function, score?
Need a hint?
Read the table.
Show the full solution
predict_proba.
predict_proba(X)[:, 1] returns [0.1, 0.45, 0.55, 0.9]. What does predict return, and what class labels do you get if you use a threshold of 0.4 instead?
Need a hint?
Default threshold 0.5.
Show the full solution
predict: [0, 0, 1, 1]. With threshold 0.4: [0, 1, 1, 1] (0.45 now counts as class 1).
A colleague writes SGDClassifier().fit(X, y) and calls it logistic regression. Is it? Fix it.
Need a hint?
Check the default loss.
Show the full solution
No: the default loss is 'hinge', a linear SVM. Use SGDClassifier(loss="log_loss").
For LogisticRegression, C=0.1 versus C=10: which is more regularised, and which is more likely to overfit?
Need a hint?
C is the inverse of the strength.
Show the full solution
C=0.1 is more regularised; C=10 is more likely to overfit.
Exam radar
MLP: logistic regression is the topic of week 5 and appears in classification questions throughout; predict_proba/decision_function and the effect of C are standard. Look for: "What is the shape of coef_ for a 3-class problem?", "Which method returns class probabilities?", "What does decreasing C do?", "What is the default loss of SGDClassifier and which model is that?", and probability-from-weights calculations.
From MLT, logistic regression shows up in 23 End Term papers, and the sigmoid in 10.
predict_probareturns one column per class, in the order ofclasses_.Cis the inverse of regularisation strength.SGDClassifier's default is hinge (SVM), not logistic.scoreis accuracy, not likelihood.- Binary
coef_has shape(1, n_features). - Scale the features and raise
max_iterif there is a convergence warning.
Quick quiz
With the default settings, LogisticRegression predicts class 1 when...
- the score is negative
- the probability of class 1 exceeds 0.5
- the probability exceeds 0.9
- the weights are positive
A 3-class LogisticRegression is fitted on 5 features. The shape of coef_ is...
- (5,)
- (5, 3)
- (3, 5)
- (1, 5)
Decreasing C in LogisticRegression...
- weakens the regularisation
- strengthens the regularisation
- changes the number of classes
- turns off the bias
Select all TRUE statements. (select all that apply)
- predict_proba rows sum to 1.
- SGDClassifier needs loss="log_loss" to behave like logistic regression.
- The default loss of SGDClassifier is log_loss.
- decision_function returns probabilities.
Recap
- , ; boundary ;
decision_function,predict_proba,predict= threshold at 0.5. LogisticRegressiondefaults:C=1.0, ,lbfgs,max_iter=100. SmallC= strong regularisation.- Multi-class: one weight row per class, softmax,
coef_.shape=(K, d). SGDClassifier(loss="log_loss")= incremental logistic regression (default loss ishinge).
- ; softmax
- Log loss
predict_proba;decision_functionbinary, multi-class;coef_or
- MLF week 9 - Optimising with rules: Lagrange and KKT: Logistic regression in sklearn.
- MLT week 9 - Perceptron and logistic regression: Logistic regression: the theory, then the code.
Practise with real exam questions
These come straight from past papers (with the real figures and the official answer key). Open 28 real questions on this week All Quiz 2 papers