A Second Model: Logistic Regression

A decision tree predicts by asking questions one after another. Logistic regression works differently. It gives every feature a weight, adds up the evidence from all features at once, and turns the total into a probability: a number between 0 and 1 that says how likely the model thinks a yes is. That gives you more than a bare yes or no, and the weights it learns tell you which way each feature pushes the answer.

Adding up the evidence: the weighted sum

Take a small example: a gym wants to predict which members will cancel their membership next month. For each member it knows three numbers: how many visits they made last month, how many months they have been a member, and how many late payments they have had.

A linear model gives each feature a weight, a number it learns from the training rows. To score one member, it multiplies each feature by its weight and adds the results, then adds one more learned number, the intercept, which is the starting point before any feature is counted. The total is the weighted sum.

Suppose the model learned a weight of −0.30 per visit, −0.05 per month of membership, +0.80 per late payment, and an intercept of 1.0. Here is the arithmetic for one member:

One member, scored
FeatureValueWeightValue × weight
intercept+1.00
visits last month3−0.30−0.90
months as member10−0.05−0.50
late payments1+0.80+0.80
weighted sum+0.40

Each feature pushes the total up or down. A positive weight means more of that feature raises the sum, toward "will cancel". A negative weight means more of it lowers the sum, toward "will stay". Frequent visits and a long membership pull this member's score down; the late payment and the intercept push it up, and the pushes up win by 0.40.

Written as a formula, with features \( x_1, x_2, x_3 \), weights \( w_1, w_2, w_3 \) and intercept \( w_0 \):

$$z = w_0 + w_1 x_1 + w_2 x_2 + w_3 x_3$$

weighted sum

The model is called linear because each feature adds its own straight-line share to \( z \): one more late payment always adds exactly 0.80, whatever the other features are. Training means finding the weights and the intercept that make the sums fit the known answers of the training rows as well as possible.

True or false?

In a weighted sum, a feature with a negative weight can only lower the total when its value goes up.

True. Its share is value times weight. With a negative weight, a larger value gives a more negative share, so the total goes down.

A linear model looks at its features one at a time, like the questions of a decision tree.

False. It uses every feature at once: all their shares are added into one total.

From a sum to a probability

A weighted sum can be any number: −7, 0.4 or 12. A probability must lie between 0 and 1. Logistic regression is the linear model for yes-or-no answers that bridges the gap. It passes the weighted sum \( z \) through the logistic function (also called the sigmoid), which squeezes any number into that range:

$$p = \frac{1}{1 + e^{-z}}$$

probability of yes

Here \( e \) is a fixed number, about 2.718, and you never need to compute the formula by hand. What matters is the shape of the curve it draws:

The logistic function

probability of yes against weighted sum z

  • p = 1 / (1 + e^(−z))
  • A sum of exactly 0 gives a probability of exactly 0.5: the model cannot lean either way.
  • A positive sum gives more than 0.5, a negative sum less than 0.5.
  • The curve only rises, so a larger sum always means a larger probability.
  • The curve never reaches 0 or 1. A very large sum gives a probability very close to 1, never 1 itself.

Call the member scored above member C. Their sum of 0.40 becomes a probability of about 0.60 of cancelling. Member A visits often and has paid on time: their sum might be −2.6, a probability of about 0.07. Member B has two late payments and almost no visits: their sum might reach 2.15, about 0.90.

The curve is steep around 0.5 and flat near both ends. Adding 1 to a sum near 0 moves the probability by more than 0.2; adding 1 to a sum of 5 moves it by less than 0.01. Keep that in mind when you read the weights later: a weight says how much the sum changes, not how much the probability changes.

Despite its name, logistic regression is a classifier: it answers a yes-or-no question. The name comes from the logistic function at its heart.

True or false?

If the weighted sum of a row is 0, logistic regression gives that row a probability of 0.5.

True. e to the power 0 is 1, so the formula gives 1 / (1 + 1) = 0.5.

Adding 1 to the weighted sum always raises the probability by the same amount.

False. The curve is steep near 0.5 and flat near 0 and 1, so the same step in the sum moves the probability a lot in the middle and very little at the ends.

A probability for each answer

Because the model ends in a probability, it can tell you more than its answer. In scikit-learn, every classifier that gives probabilities has a method predict_proba. For a yes-or-no question it returns two numbers per row: the probability of each answer. The two always add up to 1, so a 0.60 chance of yes means a 0.40 chance of no.

Probabilities and the predicted answer
MemberProbability of noProbability of yesPredicted answer
A0.930.07no (stays)
C0.400.60yes (cancels)
B0.100.90yes (cancels)

The bare answer that predict returns follows a simple default rule: it picks the more probable answer, which for two answers means yes whenever the probability of yes is above 0.5. A probability above 0.5 is the same as a weighted sum above 0, so scikit-learn applies the same rule directly to the sum: a positive sum means yes. A row at exactly 0.5 gets the first answer in the model's list of answers.

The table shows why the probability is worth having. Members C and B both get the answer "yes", but the model is far surer about B (0.90) than about C (0.60). The bare answer throws that difference away; the probability keeps it. Treat it as the model's own estimate, learned from its training rows, not as a guaranteed chance.

In code, the columns of predict_proba come in the order of the model's classes_ attribute, which lists the answers sorted: for the labels 'No' and 'Yes', column 0 is the probability of 'No' and column 1 the probability of 'Yes'.

Probabilities and answers for new rows
proba = model.predict_proba(X_new)   # one row per member, one column per answer
p_yes = proba[:, 1]                  # column 1 of every row: the probability of 'Yes'

answers = model.predict(X_new)       # 'Yes' where p_yes is above 0.5, else 'No'

proba[:, 1] reads "every row, column 1": the colon means all rows. model.classes_ shows which answer each column belongs to.

True or false?

For a yes-or-no question, predict_proba returns a single probability per row.

False. It returns two columns, one per answer, in the order of classes_. They add up to 1, and the probability of the second answer is column 1.

With the default rule, a row whose probability of yes is 0.51 gets the answer yes, just like a row at 0.99.

True. The default rule only asks which answer is more probable. The probability keeps the difference in confidence that the bare answer drops.

Training a logistic regression in scikit-learn

Logistic regression follows the same fit and predict pattern as every scikit-learn model. It lives in the module sklearn.linear_model. Every feature must be a number with no blank values, because the model multiplies each feature by its weight.

Fit, then look at what was learned
import pandas as pd
from sklearn.linear_model import LogisticRegression

model = LogisticRegression()
model.fit(X_train, y_train)

print(model.classes_)         # the answers, sorted: column order of predict_proba
print(model.intercept_[0])    # the intercept w0

weights = pd.Series(model.coef_[0], index=model.feature_names_in_)
print(weights)                # one learned weight per feature, labelled by name

After fit, the learned numbers sit in attributes that end with an underscore. coef_ holds the weights: for a yes-or-no question it is a table with one row, so coef_[0] is the list of weights, one per feature, in the order of the training columns. intercept_[0] is the intercept.

When the model was trained on a pandas table, feature_names_in_ keeps the column names. pd.Series(values, index=names) builds a pandas column of the weights, each labelled with its feature name, so you can read them side by side.

The weights point toward the second answer in classes_. With the answers 'No' and 'Yes', a positive weight pushes toward 'Yes'.

Two defaults are worth knowing.

First, scikit-learn adds a gentle brake on the weights, called regularization, which keeps them from growing large to fit every quirk of the training rows. Its strength is set with the parameter C, which is 1.0 by default; a smaller C brakes harder, and C=np.inf removes the brake. Older tutorials also pass a parameter called penalty, which picks the kind of brake or switches it off. It is deprecated since scikit-learn 1.8: leave it out to keep the default brake, and write C=np.inf where a tutorial writes penalty=None.

Second, the default solver (the routine that searches for the weights) involves no randomness, so the fit gives the same weights on every run without a seed. If the search stops before it settles, scikit-learn prints a ConvergenceWarning; that tends to happen when features have very different ranges.

Reading the weights

The sign of a weight is the part you can read straight away. A positive weight means that, for rows that are otherwise alike, more of that feature makes the model lean toward yes; a negative weight means it leans toward no. In the gym example, the weight of +0.80 for late payments says the model sees late payments as a sign of cancelling, and the negative weight for visits says frequent visitors look like members who stay.

The size of a weight is harder. A weight is the change in the weighted sum for one more unit of the feature, so its size depends on the unit the feature is measured in. Look at what happens when the same information is measured in two ways:

Same information, different unit
FeatureOne unit isWeightShare for a 2-year member
membership length1 month−0.0524 × −0.05 = −1.2
membership length1 year−0.602 × −0.60 = −1.2

Measured in years, membership gets a weight about twelve times larger, yet it says the same thing and adds the same share to the sum. Nothing about the feature became more important; only its unit changed. The same trap appears between different features: a weight per visit and a weight per month are in different units, so −0.30 being larger than −0.05 tells you nothing about which feature matters more. A feature that takes large values, such as a price in cents, can have a tiny weight and still move the sum a lot.

Sizes can only be compared when the features share a scale, for example after every feature has been rescaled so that its values spread out by the same amount. Until then, read the signs as directions and leave the sizes alone.

Two more limits apply even then. A weight describes the push of a feature with the other features held fixed, and when two features carry much the same information, the model can split the weight between them in an unstable way. And a weight describes what the model uses to predict, not a cause: a negative weight for visits does not show that getting members to visit more would stop them from cancelling.

True or false?

A weight of 2.0 always shows a more important feature than a weight of 0.5.

False. Each weight is per unit of its own feature. If the features are measured on different scales, the sizes cannot be compared, only the signs.

Changing a feature from months to years changes its weight but not the direction it pushes the prediction.

True. The weight grows to match the larger unit, but its sign stays the same, and so does the share the feature adds to the sum.

A positive weight for a feature proves that the feature causes the yes answer.

False. A weight describes what the model relies on to predict, with the other features held fixed. It says nothing about what would change the outcome.