Classification in Machine Learning: Logistic Regression, KNN

Learn how machine learning models sort examples into categories. Build logistic regression from the sigmoid function, read its predicted probabilities and decision boundaries, and train it by minimizing log loss with gradient descent and in scikit-learn. Extend it to many classes with one-vs-rest and softmax, classify with k-nearest neighbors, get an overview of naive Bayes and linear discriminant analysis as classifiers built on Bayes' theorem, and handle data in which one class is rare.

IntermediateLesson 3 of 9 in Machine Learning Course

What you will learn

  1. Recognize classification problems, turn a linear score into a probability with the sigmoid function, and read the decision boundary that separates the predicted classes.
    • Recognize classification tasks and why linear regression falls short
      Tell classification apart from regression, encode class labels, and explain why fitting a straight line to 0/1 labels gives poor classifiers.
    • Turn a linear score into a probability with the sigmoid function
      Compute logistic regression predictions, connect probabilities with odds and log-odds, and read what a weight does to a prediction.
    • Draw and interpret decision boundaries
      Locate the boundary where predictions switch class, move it by changing the threshold, and bend it with engineered features.
  2. Measure how well predicted probabilities fit the labels, fit the weights with gradient descent, and train and read a logistic regression model in scikit-learn.
    • Measure prediction quality with log loss
      Compute the log loss of single predictions and of a training set, and explain why it replaces squared error for classification.
    • Fit the weights with gradient descent
      Apply the gradient descent update to logistic regression, carry out an update by hand, and recognize convergence problems and their fixes.
    • Train and read logistic regression in scikit-learn
      Fit a logistic regression model in Python, get probabilities and classes with any threshold, and read the fitted weights with care.
  3. Extend binary classification to many classes, either by combining binary classifiers or by predicting all class probabilities at once with softmax.
    • Combine binary classifiers with one-vs-rest and one-vs-one
      Build multiclass classifiers from several binary ones, predict with them, and know their costs and quirks.
    • Predict class probabilities with softmax regression
      Compute softmax probabilities and the cross-entropy loss, and choose correctly between multiclass and multilabel set-ups.
  4. Predict a class from the most similar training examples, and choose the number of neighbors and the feature scaling that make those predictions reliable.
    • Predict by a vote of the nearest neighbors
      Measure distances, find the k nearest training examples, and turn their votes into a class and a probability.
    • Choose k and prepare features for kNN
      Pick the number of neighbors with validation data, scale the features so that each one counts fairly, and recognize when kNN struggles.
  5. Use Bayes' theorem to turn class priors and feature distributions into class probabilities, get an overview of naive Bayes, linear and quadratic discriminant analysis, and compare all the classifiers in this unit.
    • Build a classifier from Bayes' theorem
      Contrast generative and discriminative models, and compute posterior class probabilities from priors and likelihoods.
    • Classify with naive Bayes
      Apply the naive independence assumption, compute a prediction by hand, handle unseen words with smoothing, and know the main variants.
    • Understand linear and quadratic discriminant analysis
      Explain the assumptions behind LDA and QDA, locate an LDA boundary in one dimension, and compare LDA with logistic regression.
    • Compare classifiers and choose one for a task
      Weigh logistic regression, k-nearest neighbors, naive Bayes and discriminant analysis by boundary shape, data needs, speed, probabilities and interpretability.
  6. Recognize when one class is rare and how that misleads training, then rebalance with class weights, resampling and a better threshold without distorting the test data.
    • Recognize class imbalance and its effects
      Spot imbalanced data, see why accuracy hides failure on the rare class, and understand how imbalance shapes what each classifier learns.
    • Rebalance training with class weights, resampling and thresholds
      Apply class weights, oversampling, undersampling, SMOTE and threshold moving, and keep validation and test data untouched.

Classification in Machine Learning study guide

6 chapters

1

From features to a predicted class

A yes-or-no prediction needs both a model of the evidence and a rule for making a decision. Logistic regression connects those jobs: a weighted score becomes a probability, and a threshold turns that probability into a class. You will calculate each stage, interpret weights through odds, and see how a boundary changes when you change features or the cutoff. These distinctions matter when two models predict the same classes but express different confidence.

1.1 Categories, labels, and model outputs

Predicting whether a machine part will fail is a classification task. Predicting its remaining lifetime in hours is a regression task. Both use labeled training examples, but the kind of target determines what the output must mean.

Describe one training example

An example has a feature vector 𝐱=(x1,…,xn) and a target label y. Features might include operating temperature in °C and vibration measured by a sensor. A training set contains m examples. A linear scoring model assigns a weight to each feature and adds a bias, also called an intercept.

In binary classification, code the class to detect as 1 and the other as 0. For a failure detector, “failed” can be the positive class and “working” the negative class. Positive describes the label's role; a failure is still an unwanted event. Keep this mapping fixed when training, extracting probabilities, and making decisions.

Multiclass classification has at least three possible classes. A support ticket might be labeled “billing,” “technical,” or “account.” Assigning codes 0, 1, and 2 makes the labels convenient to store. It does not make “technical” halfway between the other two classes.

Separate probability from a decision

A classifier may return a class directly, or it may first produce a score or probability. Logistic regression estimates p^=P(y=1∣𝐱). This is a probability for the positive class given the features. The negative-class probability is 1−p^.

For example, an estimated failure probability of 0.72 becomes class 1 under a 0.5 threshold. The value 0.72 describes the model's uncertainty; the label 1 describes the decision. Raising the cutoff to 0.8 changes the decision for this part while leaving its estimated probability at 0.72.

Why fitting a line to labels causes trouble

Linear regression can fit a straight line to binary labels, but its outputs are unrestricted. Values such as −0.2 and 1.3 cannot serve as probabilities. Applying a cutoff does not repair that probability interpretation.

The fitted line can also respond badly to extreme feature values. Imagine using temperature to predict failure. Adding a correctly labeled failure at a very high temperature can flatten the fitted line. Its crossing of 0.5 then moves upward, causing some moderate-temperature failures to be classified as working. The new observation confirmed failure at high temperature, yet shifted decisions in an unhelpful direction.

For three or more classes, regression on integer codes adds a second problem: it treats category names as equally spaced quantities. Changing the numerical coding would change those supposed distances. A classification model represents the categories without imposing that artificial scale.

Key Takeaways

  • Classification predicts categories; regression predicts a numerical quantity.
  • The positive class is coded 1 and names the event to detect.
  • A probability estimate and the class chosen by a threshold are different outputs.
  • Linear regression can leave the probability range and treats multiclass codes as a numerical scale.

1.2 Scores, sigmoid probabilities, and odds

Logistic regression begins with the same kind of weighted sum as linear regression. Its extra step is the sigmoid, which turns that unrestricted score into a probability.

Calculate the score, then the probability

For weights 𝐰 and bias b, calculate

z=𝐰⋅𝐱+b,p^=σ(z)=11+e−z.

The score can be any real number. The sigmoid is increasing and S-shaped, with outputs strictly between 0 and 1 for finite scores. At z=0 it gives 0.5. Large positive scores approach probability 1; large negative scores approach 0. Its symmetry gives σ(−z)=1−σ(z), so scores 2 and −2 give about 0.881 and 0.119.

Consider the exam-pass model z=1.5x−6, where x is hours of study. At 3 hours, the score is −1.5 and the probability is about 0.182. At 4 hours, the score is 0 and the probability is 0.5. At 5 hours, the score is 1.5 and the probability is about 0.818. At 6 hours it is 3, giving about 0.953. Under the inclusive 0.5 rule, the model predicts a pass from 4 hours.

Interpret a weight through odds

Probability and odds describe the same estimate on different scales:

odds=p1−p,log-odds=ln⁡p1−p.

For a logistic model, the log-odds equal the score z. Raising one feature by one unit while holding the others fixed adds its weight to the log-odds. Equivalently, it multiplies the odds by the exponential of that weight.

In the study-hours model, one extra hour multiplies the odds by e1.5≈4.48. At 4 hours, the odds are 1. At 5 hours they are about 4.48. A positive weight increases the predicted probability, a negative weight decreases it, and a zero weight leaves it unchanged when the other features stay fixed.

A weight is not a fixed probability change

Adding 0.8 to a score of 0 changes the probability from 0.5 to about 0.690. Adding the same 0.8 to a score of 3 changes it from about 0.953 to 0.978. The curve is steep near its center and flatter near its ends. Reading a weight of 0.8 as an increase of 0.8 in probability would confuse these scales.

In scikit-learn, decision_function returns scores and predict_proba returns probabilities. A score of 2 is valid; a probability of 2 is not.

A predicted probability describes the model's estimate for cases with those features. A well-calibrated model assigning 0.8 to many cases should see roughly 80% positives among them. Each individual outcome is still either positive or negative; it is not partly in each class.

Key Takeaways

  • The sigmoid converts a real-valued score into a probability between 0 and 1.
  • A zero score gives probability 0.5; opposite scores give complementary probabilities.
  • A one-unit feature increase adds its weight to log-odds, holding other features fixed.
  • The same increase multiplies the odds by the exponential of the weight.
  • Weights do not describe constant changes in probability.

1.3 Where predictions switch class

A decision boundary marks where the predicted class changes. Its position depends on the scoring model and on the threshold used to turn probabilities into classes.

Find the boundary at a 0.5 threshold

Use the rule “predict class 1 when p^≥0.5.” The sigmoid reaches 0.5 exactly at score 0, so the boundary satisfies

𝐰⋅𝐱+b=0.

With two features this is a line; with three it is a plane. In higher dimensions it is a flat hyperplane. Logistic regression using the original features is therefore a linear classifier, even though its probability curve is not a straight line.

For weights 1 and 1 and bias −3, the boundary is x1+x2=3. At (2,2) the score is 1, giving probability about 0.731 and class 1. At (1,1) the score is −1, giving about 0.269 and class 0. At (3,0) the score is 0 and the probability is exactly 0.5; the inclusive rule assigns class 1.

Read direction and confidence

The weight vector is perpendicular to the boundary and points toward the positive side. For fixed nonzero weights, signed perpendicular distance equals z/∥𝐰∥. Points farther into the positive side therefore have larger scores and probabilities closer to 1.

Multiplying every weight and the bias by 10 leaves the zero-score line unchanged. At (2,2) the score becomes 10 and the probability becomes about 0.99995. The class regions stay the same at a 0.5 cutoff, but the confidence changes sharply.

Move the threshold

For a threshold 0<t<1, classify as positive when

z≥ln⁡t1−t.

At t=0.8, the needed score is about 1.386. The example's boundary moves to x1+x2=4.386, shrinking the positive region. At t=0.3, it moves to x1+x2=2.153, expanding that region. The weights stay fixed while the decision rule changes.

Bend the boundary with features

Suppose the model uses squared features with score z=x12+x22−1. Its 0.5 boundary is the unit circle, x12+x22=1. Outside the circle the score is positive. The model is linear in the weights applied to the engineered features, while the boundary is curved in the original coordinates.

Adding polynomial features increases flexibility and can increase overfitting. When classes overlap, some errors are expected even for a useful boundary. Chasing every training point can fit noise that will not repeat in new data. LDA gives flat boundaries, QDA can give quadratic boundaries, and kNN follows local training neighborhoods with irregular boundaries.

Key Takeaways

  • At a 0.5 threshold, the logistic boundary is the zero-score set.
  • The weight vector points perpendicular to the boundary toward the positive side.
  • Positive rescaling of all parameters preserves the 0.5 boundary but changes confidence.
  • A higher threshold shrinks the positive region without retraining.
  • Engineered features can produce curved boundaries in the original coordinates.
  • Overlapping classes can leave errors on both sides of a useful boundary.
2

Fit probabilities with log loss

A prediction becomes useful through training: the model must learn which scores fit the observed labels. Log loss measures the quality of its probabilities, and an optimizer changes the weights to reduce that cost. You will work through a gradient update and then connect the calculation to a scikit-learn pipeline. Reading probabilities, checking convergence, and interpreting scaled coefficients are all parts of fitting a model you can use on new cases.

2.1 How log loss judges a probability

Class labels discard confidence. For a positive example, probabilities 0.51 and 0.99 both produce class 1 at a 0.5 cutoff, but they express very different predictions. Log loss measures that difference before any threshold is applied.

Use the probability of the observed class

For a positive label, the probability assigned to the observed outcome is p^. For a negative label it is 1−p^. Take the negative natural logarithm of that probability:

L=−[yln⁡p^+(1−y)ln⁡(1−p^)].

When y=1, this reduces to −ln⁡p^. When y=0, it reduces to −ln⁡(1−p^). The inactive term drops out. The names binary cross-entropy, logistic loss, and binary log loss describe this same objective.

For a positive example, a prediction of 0.9 gives loss about 0.105. At 0.5 the loss is about 0.693; at 0.1 it is about 2.303; at 0.01 it is about 4.605. Confident wrong predictions are especially costly. As the probability of the true outcome approaches 1, loss approaches 0. As it approaches 0, loss grows without bound.

Average the examples

The training cost is the mean of the individual losses:

J(𝐰,b)=1m∑i=1mLi.

For labels and predictions (1,0.8),(1,0.6),(0,0.3),(0,0.1), the observed-class probabilities are 0.8, 0.6, 0.7, and 0.9. Their losses are about 0.223, 0.511, 0.357, and 0.105. The mean is about 0.299. For the negative example with prediction 0.3, using −ln⁡0.3 would penalize the wrong probability; use −ln⁡0.7.

Always predicting 0.5 gives loss ln⁡2≈0.693 for every binary example. This is a useful reference for an uninformative 50–50 model. With unequal class shares, a constant estimate equal to the positive share can improve on that reference.

Why use this training objective?

Squared error combined with a sigmoid is not convex in the weights and can have flat regions that slow or stall optimization. Its penalty for a confidently wrong binary prediction is also capped at 1. Logistic log loss is convex in the weights and bias: any attained local minimum is global. Perfectly separable unpenalized data can still lack a finite minimizing parameter vector.

Minimizing log loss also maximizes the likelihood of the observed yes-or-no labels. The product of their assigned probabilities becomes a sum after taking logarithms, linking probability modeling directly to the training objective.

Log loss is never negative. A prediction of exactly zero for a true positive has infinite theoretical loss; software clips extreme probabilities for numerical calculation. With many classes, take the negative logarithm of the probability assigned to the true class. Two models can predict identical classes and still have different losses.

Key Takeaways

  • Log loss is the negative natural log of the probability assigned to the true class.
  • For a negative label, use the complement of the positive-class probability.
  • The model cost is the mean loss across examples.
  • Confident wrong predictions receive a large, unbounded penalty.
  • Logistic log loss is convex in its parameters; an attained local minimum is global.

2.2 One gradient step and what it means

Training changes weights and bias to reduce the average log loss. Gradient descent computes the slope of the cost with respect to every parameter, then moves against those slopes.

Compute all gradients at the current parameters

For each example, calculate its sigmoid probability and error p^i−yi. The gradients are

∂J∂wj=1m∑i(p^i−yi)xij,∂J∂b=1m∑i(p^i−yi).

Then use learning rate α:

wj:=wj−α∂J∂wj,b:=b−α∂J∂b.

Compute every gradient before changing any parameter. Recomputing the bias gradient after updating a weight would mix two different parameter states within a single step. The error uses the probability, not the raw score.

Work through an update

Take one feature with values 1, 2, 3, and 4 and labels 0, 0, 1, and 1. Start with weight 0, bias 0, and learning rate 0.1. Every score is 0, so every probability is 0.5. The four errors are 0.5, 0.5, −0.5, and −0.5.

For the weight gradient, multiply each error by its feature value and average:

0.5(1)+0.5(2)−0.5(3)−0.5(4)4=−0.5.

The bias gradient is the mean error, which is 0. Thus the new weight is 0−0.1(−0.5)=0.05 and the bias stays 0. Recomputing predictions gives a cost decrease from about 0.6931 to 0.6705. The positive weight raises scores more for the larger feature values, which belong to the positive examples.

An example with a small prediction error contributes little to the update. A badly predicted example contributes more, and large feature values magnify its contribution to that feature's gradient.

Read a training trace

Plot cost against iteration. A suitable learning rate makes this full-batch objective fall and level off. A rate that is too large can make cost rise or oscillate; one that is too small can make progress very slow. Standardizing features to mean 0 and standard deviation 1 often improves the geometry of the optimization.

Logistic regression has no normal-equation solution like ordinary linear regression. The parameters require an iterative optimizer. Libraries often use faster optimization methods such as L-BFGS instead of a basic gradient loop.

Understand growing weights

With perfectly separable data, multiplying separating parameters by larger positive values makes the correct probabilities approach 0 or 1. Unpenalized log loss keeps falling without reaching its infimum at finite weights. Convexity does not guarantee a finite minimizer. Regularization penalizes large weights, and early stopping can also keep the fitted parameters finite. Scikit-learn applies an L2 penalty by default; a smaller C means stronger regularization.

Key Takeaways

  • Each error is the sigmoid probability minus the observed label.
  • Compute every gradient from the same current parameters before updating.
  • The weight gradient averages error times feature; the bias gradient averages error.
  • Learning rate and feature scaling affect convergence.
  • Logistic regression uses iterative optimization.
  • Perfect separation can drive unpenalized weights without limit; a penalty controls that growth.

2.3 A pipeline you can fit and inspect

A fitted classifier includes the transformations applied to its inputs. Keeping scaling and logistic regression together makes training and later predictions use the same feature definitions.

Fit the training data

X_train is a two-dimensional array: one row per example and one column per feature. y_train contains one label per row. A basic scaled model is:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

pipe = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=1000)
)
pipe.fit(X_train, y_train)

The scaler learns its means and standard deviations from the training rows. The pipeline applies that same fitted transformation to later inputs. Fitting a new scaler on test data would give a different transformation and use information unavailable during training.

LogisticRegression() fits an intercept and uses the "lbfgs" solver, an L2 penalty with C=1.0, and a default iteration limit of 100. The example increases that limit. A ConvergenceWarning indicates the optimizer did not satisfy its stopping criterion; check scaling and consider increasing max_iter. More iterations do not fix a poorly chosen feature representation.

Read the probability columns
lr = pipe.named_steps["logisticregression"]
print(lr.classes_)
proba = pipe.predict_proba(X_new)
positive_col = list(lr.classes_).index(1)
p_positive = proba[:, positive_col]
y_at_03 = (p_positive >= 0.3).astype(int)

Each row of proba corresponds to one new example; columns follow classes_. For labels 0 and 1, column 1 is the positive probability. If labels are strings, find the desired class in classes_ instead of assuming a column. Taking column 0 for the positive class reverses the interpretation.

pipe.decision_function(X_new) returns the scores. Binary predict chooses the second class when the score is strictly positive; at exactly zero it chooses the first class. An explicit >= 0.5 probability rule includes ties in the positive class, so it differs at that exact endpoint.

Interpret coefficients on their fitted scale

The fitted weights are in lr.coef_ and the biases in lr.intercept_. A binary model has coefficient shape (1, n_features); a multinomial model has one row per class. In this pipeline the coefficients apply to standardized features.

For a customer-cancellation model, a weight of −0.8 on “minutes of weekly use” means that one extra training standard deviation of use subtracts 0.8 from the log-odds, holding other inputs fixed. It multiplies the odds by e−0.8≈0.449. It does not subtract 0.8 from the cancellation probability.

Raw coefficient sizes depend on units: a length expressed in millimeters needs a coefficient 1,000 times smaller than the same length in meters. Compare magnitudes only on comparable scales. Strongly correlated features can share or exchange fitted weight, so a small individual coefficient is not a complete measure of that feature's usefulness.

Key Takeaways

  • A pipeline learns scaling during fitting and reuses it for new examples.
  • Probability columns follow the fitted class order.
  • An explicit threshold rule can differ from binary predict at an exact tie.
  • Scaled coefficients describe changes per training standard deviation.
  • Units and correlated features limit simple coefficient-magnitude comparisons.
3

Choose one class from several

More than two possible classes changes the prediction setup. You can train several binary models and combine their decisions, or fit one model that assigns probabilities to all classes together. The choice affects model counts, class balance, and what the probabilities mean. You will compare these constructions, calculate softmax probabilities, and distinguish a single multiclass label from several labels that may apply to the same example.

3.1 Combine binary decisions

A multiclass task gives each example exactly one of K≥3 labels. Binary models can solve it by breaking the training problem into smaller questions and combining their outputs.

One class against the rest

One-vs-rest, also called one-vs-all, trains one binary classifier for each class. Classifier k marks examples of class k positive and all other examples negative. At prediction time, compare the classifiers' scores or positive-class probabilities and choose the largest. A fixed tie-breaking rule resolves equal largest values.

Suppose support-ticket classifiers return 0.70 for “billing,” 0.40 for “technical,” and 0.15 for “account.” Billing wins. The outputs sum to 1.25 because separate binary models estimated them independently. They are not yet one probability distribution over the three labels.

Normalizing by their sum produces 0.56, 0.32, and 0.12. This preserves the winning class and makes the numbers sum to 1, but it does not turn the separately fitted models into a joint model. Scikit-learn's one-vs-rest wrapper uses such normalization for single-label probabilities.

Do not require a classifier to exceed 0.5 before making a multiclass prediction. If the three outputs were 0.40, 0.35, and 0.25, the largest would still select a class. Likewise, several outputs above 0.5 do not require several labels: the single-label prediction still selects a winner.

With equally common classes, each one-vs-rest problem can be imbalanced. Ten equal classes produce 10% positives and 90% negatives in each binary training problem.

One class against one other class

One-vs-one trains a classifier for every distinct pair of classes. Its model count is

K(K−1)2.

Each classifier sees only examples of its two classes. At prediction time, each pairwise model votes for one class, and the class with the most votes wins, with a fixed rule for ties. Ten classes need 45 pairwise models, compared with 10 one-vs-rest models. The larger count does not mean each fit uses the whole training set.

ConstructionBinary modelsTraining data for one modelPrediction
One-vs-restKAll examples, with one positive classHighest class score
One-vs-oneK(K−1)/2Only the two classes in that pairMost pairwise wins
Choose the construction explicitly

In scikit-learn, OneVsRestClassifier(LogisticRegression()) requests separate binary fits. OneVsOneClassifier(LogisticRegression()) requests pairwise fits. Import these wrappers from sklearn.multiclass.

With three or more classes, LogisticRegression() using its default solver fits a multinomial, or softmax, model directly. Calling it without a wrapper is therefore different from explicitly requesting one-vs-rest. kNN, naive Bayes, and discriminant analysis also handle multiclass tasks directly.

Key Takeaways

  • One-vs-rest fits one binary model per class and selects the highest output.
  • Separate one-vs-rest probabilities need not sum to 1.
  • One-vs-one fits one model per class pair and combines their votes.
  • Ten classes require 10 one-vs-rest models or 45 one-vs-one models.

3.2 Softmax probabilities and single-label predictions

Softmax regression fits all classes together. Each class has a weight vector and bias, giving a score zk=𝐰k⋅𝐱+bk. The scores become one probability distribution over the possible labels.

Normalize exponentials, not scores

The probability of class k is

p^k=ezk∑j=1Kezj.

Exponentials are positive, so every probability is positive and the probabilities sum to 1. The largest score gives the largest probability. Raw scores can be negative and cannot be normalized as probabilities just by dividing by their sum.

For scores (2,1,0) assigned to “billing,” “technical,” and “account,” first exponentiate: about 7.389, 2.718, and 1. Their sum is about 11.107. Dividing each value by that sum gives probabilities about 0.665, 0.245, and 0.090. Billing is the prediction.

Differences between scores carry the information

Adding the same constant to every score leaves the probabilities unchanged. The common exponential factor cancels from numerator and denominator. Thus (7,6,5) gives the same distribution as (2,1,0).

Software uses this property to prevent overflow: subtract the largest score before exponentiating. The original example can be evaluated as (0,−1,−2). The largest exponential is then 1, without changing any probability.

With two classes, the probability of class 1 becomes

p^1=σ(z1−z0).

Scores 0.4 and 1.2 therefore give the sigmoid of 0.8, about 0.690. Applying the sigmoid to 1.2 alone would ignore the competing score.

Train on the observed class

Multiclass cross-entropy is L=−ln⁡p^true class. In the ticket example, a truly technical ticket has loss about 1.408, while a billing ticket has loss about 0.408. The probabilities describe the same prediction, but the loss depends on which label actually occurred.

A one-hot label has 1 in the observed class's position and 0 elsewhere. “Technical” is (0,1,0), so L=−∑kykln⁡p^k selects exactly the technical-class term.

Softmax predicts the class with the largest score. A boundary between two winning class regions lies where their scores are equal and at least as large as the other scores. Linear class scores therefore give boundaries with straight pieces in the feature space.

Check whether several labels can apply

A single-label ticket belongs to one category. An article might instead have both “sports” and “business” tags. That is multilabel classification. Separate sigmoid outputs can estimate each label's probability, and several labels can be selected. Their probabilities need not sum to 1. Softmax's shared probability budget would incorrectly force competing probabilities for labels that can coexist.

Key Takeaways

  • Softmax exponentiates class scores and divides by their total.
  • Adding one common constant to all scores leaves probabilities unchanged.
  • Multiclass cross-entropy uses the true class probability.
  • With two classes, softmax is the sigmoid of the score difference.
  • Single-label multiclass probabilities sum to 1; multilabel sigmoid probabilities need not.
4

Predict from nearby examples

k-nearest neighbors uses the stored training examples themselves to make a prediction. A new point gets a class from nearby labeled points, so distance and neighborhood size become central modeling choices. You will calculate a vote, compare equal and distance-weighted probabilities, and see why measurement scales can reverse which example is nearest. The same local approach explains both kNN's flexible boundaries and its difficulties with sparse or high-dimensional data.

4.1 Distances, votes, and probability estimates

k-nearest neighbors, or kNN, stores labeled training examples. For a new point it finds the nearest k examples and predicts their most common class. It learns no feature weights. Fitting can also build a search index, but the main work happens when predictions are requested.

Measure closeness

Euclidean distance is straight-line distance:

d(𝐱,𝐱′)=∑j(xj−xj′)2.

Manhattan distance adds absolute changes along the axes, ∑j∣xj−xj′∣. Between (3,3) and (2,4), the Euclidean distance is 2≈1.414 and the Manhattan distance is 2. Scikit-learn's default Minkowski setting with p=2 gives Euclidean distance.

Sort first, then select neighbors

For a new point (3,3), consider these stored examples:

PointCoordinatesClassEuclidean distance
D(3,2)red1
B(2,4)blueabout 1.414
C(4,4)blueabout 1.414
E(5,3)blue2
F(4,1)redabout 2.236
A(1,1)redabout 2.828

With k=1, only D votes, so the prediction is red. With k=3, D, B, and C vote: two blue and one red, so blue. With k=5, E and F also vote: three blue and two red, still blue. Points outside the selected neighborhood do not vote.

Turn votes into probabilities

With equal votes, each class probability is its fraction of the selected neighbors. At k=5, blue has probability 0.6 and red 0.4. These estimates come in multiples of 1/k; they describe the neighborhood vote, not a fitted sigmoid.

With weights="distance", a neighbor at positive distance d receives weight 1/d. For the three nearest points, red receives weight 1 and blue receives about 1.414 in total. Blue still wins, but its probability is now its weight share, about 1.414/2.414=0.586. Red receives about 0.414. Counting two blue neighbors out of three would ignore the weighting rule.

For binary equal voting, odd k prevents a class-vote tie. Multiclass votes or weighted votes can still tie. Scikit-learn chooses the first class in its sorted class list when class totals tie. Equal distances at the neighborhood cutoff can also make the result depend on training-row order.

Fit cheaply, budget prediction work

KNeighborsClassifier() defaults to five uniformly weighted neighbors. fit stores the examples; predict returns labels and predict_proba returns class vote shares.

A brute-force search compares every query with every stored training point. Its work grows with examples times features. In lower dimensions, k-d trees or ball trees can skip many comparisons. The stored data still grow with the training set, making kNN an instance-based, nonparametric method.

Key Takeaways

  • kNN finds the nearest training examples before counting their class votes.
  • Euclidean distance uses squared coordinate differences; Manhattan distance uses absolute differences.
  • Uniform class probabilities are neighbor fractions.
  • Distance-weighted probabilities are shares of total neighbor weight.
  • Odd k prevents binary uniform vote ties, not every possible tie.
  • Prediction cost and storage can grow substantially with the training set.

4.2 Choose a useful neighborhood

A kNN prediction depends on which examples count as nearby and how many are allowed to vote. These choices change the boundary even though the algorithm fits no coefficient vector.

Choose k using unseen examples

A small k follows local detail. At k=1, one noisy label can create its own region: low bias but high variance. A larger k averages over more examples, smoothing the boundary and increasing bias while reducing variance. At the extreme, using all training examples with equal votes gives the same majority class everywhere.

A one-neighbor classifier predicts each training point from itself, giving zero training error when identical inputs do not carry conflicting labels. That attractive training result says little about a new point. Compare candidate values, such as odd numbers from 1 to 31, using validation data or cross-validation. Select the setting from those unseen cases, then reserve the test set for the final check.

Scaling can change the nearest point

Suppose a new driver is age 30 and drives 12,000 km per year. Driver P is age 31 and drives 15,000 km; Q is age 50 and drives 12,500 km. Their raw Euclidean distances from the query are about 3000.0 and 500.4. Kilometer differences dominate, making Q appear nearer despite the 20-year age difference.

If the training standard deviations are 10 years and 5,000 km, the standardized differences are (0.1,0.6) for P and (2.0,0.1) for Q. Their distances become about 0.608 and 2.002, reversing the order. Subtracting the same training mean from both points cancels in each difference; dividing by the training standard deviation changes the relative contributions.

A pipeline keeps this transformation consistent:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier

knn = make_pipeline(
    StandardScaler(),
    KNeighborsClassifier(n_neighbors=7)
)
knn.fit(X_train, y_train)

Learn the means and standard deviations only from training data, including within each training fold during cross-validation.

Check whether distance remains informative

Every included feature contributes to distance. Irrelevant features can make unrelated points look close or useful neighbors look far away. Removing uninformative inputs can improve the neighborhood more than changing k.

In high dimensions, observations spread out and nearby cases become scarce. Distances can become similar, making “nearest” less useful. This curse of dimensionality is a reason to prefer modest feature counts and many examples for kNN. Scaling fixes unit imbalance but does not remove irrelevant dimensions or create missing local data.

Class imbalance also acts locally. In mixed regions, common-class neighbors can outvote sparse rare cases. A well-separated rare cluster can still have mostly rare neighbors. KNeighborsClassifier has no class_weight parameter; distance weighting or training-data resampling are possible remedies, with their results checked on representative validation data.

Key Takeaways

  • Small neighborhoods are flexible and sensitive to noise; larger ones are smoother.
  • Choose k on validation data, not from training error.
  • Fit scaling on training rows and reuse it for every new point.
  • Scaling does not solve irrelevant features or sparse high-dimensional neighborhoods.
  • Rare-class failures depend on local class mix, not just the overall ratio.
5

Use class distributions to classify

Bayes' theorem builds a class prediction from two ingredients: how common each class is and how typical the observed features are within that class. Naive Bayes simplifies the feature relationships, while discriminant analysis models class shapes with normal distributions. You will calculate a posterior, compare their assumptions, and use those assumptions alongside speed, data size, and boundary shape to choose sensible candidate classifiers.

5.1 Priors, likelihoods, and posteriors

A class can be common overall but a poor match for a particular observation. Bayes' theorem combines the overall class share with how well the features fit that class.

Two routes to a class probability

A discriminative model such as logistic regression models P(y∣𝐱) directly. A generative model estimates a feature distribution within each class, P(𝐱∣y=k), and a class prior, P(y=k). It then combines them:

P(y=k∣𝐱)=P(𝐱∣y=k)P(y=k)∑jP(𝐱∣y=j)P(y=j).

The prior is the class share before considering the current features. The likelihood describes how typical those features are within the class. Their product is an unnormalized class score. Dividing by the sum of all class scores gives the posterior, the probability of the class after considering the features. For continuous features the likelihood uses a density; the normalized posterior is still a probability.

Update a spam probability

Suppose 20% of emails are spam. The word “prize” occurs in 30% of spam emails and 2% of other emails. For an email containing that word, calculate the two joint contributions:

spam:0.2(0.30)=0.06,not spam:0.8(0.02)=0.016.

The total chance of seeing the word is 0.076. Normalizing gives

P(spam∣prize)=0.060.076≈0.789.

The value 0.30 answers a different question: how often the word appears among spam emails. It is not the probability of spam among emails containing the word. Reversing the conditioning swaps the population being considered.

Ignoring priors would also change the question. If spam were much rarer, the same word frequencies would produce a smaller posterior because far more non-spam emails could contribute to the observed word.

Choose a class

The Bayes classifier selects the largest posterior. Since every class shares the same denominator, you can compare likelihood-times-prior scores without normalizing when only the winning class is needed. Normalization is necessary when reporting posterior values.

With the true distributions and equal costs for classification errors, choosing the largest posterior minimizes the error rate. In practice, distributions and priors are estimated, so the fitted classifier's quality depends on those estimates.

Priors are often the training class shares. If the training sample deliberately overrepresents one class, its shares may differ from the population where predictions will be used. Known deployment shares can be supplied as priors so that the posterior reflects the intended population.

Key Takeaways

  • A generative classifier combines feature distributions within classes with class priors.
  • Multiply likelihood by prior, then normalize across classes to get posteriors.
  • Reversing a conditional probability changes the question.
  • The largest unnormalized class score also has the largest posterior.

5.2 Naive Bayes: a fast product of feature evidence

Estimating a full joint feature distribution can require more data than you have. Naive Bayes makes a simplifying assumption: features are independent within each class. That turns one difficult distribution into several simpler ones.

Multiply feature likelihoods within a class

The assumption is

P(x1,…,xn∣y=k)=∏jP(xj∣y=k).

Independence is conditional on the class. It does not require features to be independent across the whole population. Each class score is its prior multiplied by its feature likelihoods.

Take spam prior 0.2. “Prize” appears in 30% of spam and 2% of non-spam emails; “meeting” appears in 5% of spam and 25% of non-spam emails. Looking at these two presence features for an email containing both words:

spam:0.2(0.30)(0.05)=0.003, not spam:0.8(0.02)(0.25)=0.004.

The prediction is not spam. The posterior spam probability is 0.003/0.007≈0.429. “Prize” favors spam, but the combined feature evidence and prior favor non-spam.

Match the variant to the inputs
VariantFeature modelTypical input
Gaussian naive BayesA normal distribution per feature in each classContinuous measurements
Multinomial naive BayesClass-specific probabilities for counted eventsWord counts
Bernoulli naive BayesPresent-or-absent featuresBinary word indicators

The corresponding scikit-learn classes are GaussianNB, MultinomialNB, and BernoulliNB. For Bernoulli features, absence also contributes: an absent word uses the complement of its presence probability. A two-word presence example does not stand in for every feature of a full vocabulary.

Keep unseen words from erasing a class

A zero word count would give a zero likelihood and erase the whole class product. Laplace smoothing adds one to every word count and adds vocabulary size to the total:

P(word∣class)=count+1total+V.

An unseen word among 1,000 class word occurrences with a 5,000-word vocabulary gets probability 1/6,000≈0.000167. Adding one only to the numerator would leave an invalid normalization. MultinomialNB uses add-one smoothing by default through alpha=1.0.

Many small likelihoods can multiply to a number too tiny to store. Implementations sum logarithms instead; because logarithms preserve order, the winning class is unchanged.

The independence assumption is often imperfect. Related words such as “free” and “offer” can count much of the same evidence twice, making probabilities too extreme. Naive Bayes can still rank classes well and is a useful fast text baseline. Good class decisions do not guarantee accurate probability values.

Key Takeaways

  • The naive assumption is independence of features within each class.
  • Gaussian, multinomial, and Bernoulli variants fit different feature types.
  • Laplace smoothing changes both the count and its normalizing total.
  • Logarithms prevent products of tiny likelihoods from underflowing.
  • Correlated features can make probability estimates too extreme.

5.3 LDA and QDA: shared or separate class shapes

Discriminant analysis is another generative approach. It models features within each class using a normal distribution, then applies Bayes' theorem. The key choice is whether the classes share a covariance matrix.

LDA shares the covariance

Linear discriminant analysis, or LDA, estimates a mean vector for each class, one covariance matrix shared by all classes, and the class priors. A covariance matrix describes feature spreads and how features vary together. Equal covariance allows class centers to differ while keeping the same overall shape.

The shared quadratic terms cancel when two class log-posteriors are compared. What remains is linear in the features, giving flat decision boundaries. Logistic regression can give the same kind of boundary, but fits class probabilities directly without assuming normal feature distributions.

Locate a one-dimensional boundary

Let class A have mean 2, class B mean 6, and both have standard deviation 1. With equal priors, their boundary is the midpoint, 4. The equal spreads make a point equally far from both means equally likely within the two classes.

For unequal priors, the boundary is

x∗=μA+μB2+σ2ln⁡(πA/πB)μB−μA.

With priors 0.8 for A and 0.2 for B, this gives 4+ln⁡4/4≈4.347. The boundary moves toward B, the rarer class. A receives a larger region because a point needs stronger feature evidence to overcome its larger prior. The midpoint rule therefore needs equal priors as well as equal variance.

QDA estimates each covariance separately

Quadratic discriminant analysis, or QDA, allows different covariance matrices for the classes. The quadratic terms need not cancel, allowing curved boundaries. That flexibility costs parameters and data.

With ten features, a symmetric covariance matrix has 55 distinct entries. LDA estimates 55 shared covariance entries; QDA with three classes estimates 165. Both also need class means and priors. When the training set is small, the shared estimate can be steadier. QDA becomes attractive when enough data support genuinely different class spreads.

MethodWhat it assumes about feature distributionsBoundary on original features
LDANormal classes with shared covarianceFlat
QDANormal classes with separate covariancesQuadratic
Logistic regressionNo class-conditional normality assumptionFlat

LDA can be stable with few examples and roughly normal classes, including strongly separated classes that cause unpenalized logistic coefficients to grow. Logistic regression often handles clearly non-normal inputs more naturally. Neither method is guaranteed to win on every data set.

Use labels to reduce dimensions

LDA can also project data into directions chosen to separate the classes. It yields at most the smaller of K−1 and the feature count. Three classes therefore need no more than two such directions. Unlike PCA, this projection uses the labels.

Scikit-learn provides LinearDiscriminantAnalysis and QuadraticDiscriminantAnalysis. Their default priors come from training class shares; priors can supply different shares. LDA's n_components respects the same dimension limit.

Key Takeaways

  • LDA assumes normal class distributions with one shared covariance matrix.
  • QDA allows different class covariances and quadratic boundaries.
  • Unequal priors shift an LDA boundary away from the equal-prior midpoint.
  • QDA estimates more covariance parameters and usually needs more data.
  • Logistic regression fits a linear boundary without normal feature distributions.
  • LDA dimension reduction uses labels and has at most min(K − 1, feature count) directions.

5.4 Choose candidates that fit the task

A useful first model matches the feature type, available data, and work the system must do at prediction time. Boundary shape alone is not enough to choose a classifier.

Compare the main tradeoffs
ModelBoundary on original inputsWhat fitting keepsMain practical issue
Logistic or softmax regressionFlat unless features are engineeredWeights and biasesIterative fitting; feature representation matters
kNNFlexible local shapesTraining examples and possibly an indexDistance, storage, and prediction cost
Naive BayesDepends on the variant; Gaussian can curveClass priors and feature distributionsConditional independence can distort probabilities
LDAFlatMeans, shared covariance, priorsShared normal class shape
QDAQuadraticMeans, separate covariances, priorsMore parameters and greater data needs

Logistic regression, naive Bayes, LDA, and QDA are parametric: for a fixed input dimension and class set, they summarize the data with a fixed collection of parameters. kNN is nonparametric and keeps more information as more examples are added.

Match features and data volume

For 50,000 short product reviews with a 20,000-word vocabulary, multinomial naive Bayes and penalized logistic regression are sensible starting points. Counts suit the multinomial model, while a penalty helps logistic regression handle many features. Raw text vectors are high-dimensional, which makes straightforward kNN distances less promising.

For 5,000 observations from two sensors with a curved normal/faulty boundary, standardized kNN can follow local shape. Logistic regression with polynomial features is another candidate. LDA or QDA fit naturally when class measurements are roughly normal; choose shared or separate covariance according to how much data support the extra flexibility.

Budget training and prediction separately

Naive Bayes can fit quickly from counts or simple feature summaries. LDA estimates means and a shared covariance; its cost grows with feature count. Logistic regression requires iterative optimization. kNN can fit cheaply by storing points and perhaps building an index, but a large stream of predictions can make its neighbor searches expensive.

For an explanation, logistic weights show changes in log-odds, LDA displays class centers and separating directions, and kNN can show the actual neighbors behind a vote. These are different kinds of interpretation. Correlated features still complicate a coefficient-based explanation.

Compare probability behavior too

When its linear form fits well, logistic regression trained with log loss often gives useful probabilities. Naive Bayes can become overconfident when feature evidence is dependent. Uniform kNN gives coarse fractions in steps of 1/k; weighted kNN gives shares of total distance weight. A flexible boundary does not by itself make probabilities trustworthy.

Start with a simple baseline, then compare plausible candidates on validation data. When performance is similar, prefer the simpler model that meets the prediction and explanation needs. Keep the final test set separate from those choices.

Key Takeaways

  • Choose candidates from feature type, boundary shape, data size, and prediction workload.
  • Parametric models keep a fixed-size parameter summary for fixed features and classes.
  • kNN retains examples and spends much of its work at prediction time.
  • Boundary flexibility, interpretability, and probability quality are separate considerations.
6

Learn when the positive class is rare

A model can achieve high accuracy while missing every event it was built to detect. Rare classes change how training losses, local votes, and prior probabilities influence a decision. You will compare a classifier with the majority-class baseline, then choose among weighting, resampling, and moving the threshold. The workflow keeps validation and test data representative so that apparent gains survive contact with the class mix the model will actually face.

6.1 Why high accuracy can hide a failed detector

Class imbalance means one class is much rarer than another. Fraud, equipment faults, and customer cancellation can all create tasks where the event of interest supplies only a small share of the training examples.

Establish the majority-class baseline

Suppose 10 of 1,000 payments are fraudulent. A model that always predicts “legitimate” is correct on 990 payments: 99% accuracy. It detects none of the ten frauds. High accuracy alone therefore hides complete failure on the event the model is meant to find.

Compare a proposed model with that baseline and count how many actual rare cases it flags. A detector that catches some fraud can have lower overall accuracy if it also sends legitimate payments for review. Whether that tradeoff is useful depends on the consequences of a missed event and an unnecessary check.

Follow the effect through different classifiers

In ordinary logistic training, the common class supplies most terms of the average loss. Each term still depends on its probability, so a few badly predicted rare cases can contribute large losses. A rare class that occupies a distinct feature region can still be learned confidently.

The harder case is overlap. If a feature pattern occurs mostly among legitimate payments, a well-fitting model can give low fraud probabilities to that pattern even when some frauds occur there. Many of those frauds then fall below the default 0.5 cutoff.

In kNN, the same difficulty appears through local votes: common-class points may outnumber rare examples in mixed neighborhoods. It does not follow that every rare point is lost; a well-separated rare cluster can have mostly rare neighbors. Naive Bayes and LDA express class frequency through their priors, favoring the common class when feature evidence is weak.

A low probability can still identify elevated risk

If fraud occurs in 1% of payments, an estimated probability of 0.15 is 15 times the background rate. It is below 0.5 but can still identify a useful group for review. The default threshold is a decision setting, not a requirement to ignore all lower probabilities.

The estimate should still be read on its probability scale. Elevated risk does not make fraud the more likely of the two outcomes for that payment. It can justify a check because the cost of missing fraud is different from the cost of checking a legitimate case.

Preserve rare examples in the split

A stratified split keeps class shares approximately similar across subsets:

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, stratify=y, random_state=17
)

With only ten rare cases, an ordinary random split can leave very few or none in one subset. Stratification helps distribute the available cases but cannot create more evidence. Ten rare observations remain a small basis for learning, whatever the majority count. Collecting more rare-class examples can be more valuable than changing the algorithm.

Key Takeaways

  • Compare accuracy with an always-majority classifier.
  • Check how many actual rare cases are detected.
  • Imbalance is hardest where class feature distributions overlap.
  • A probability below 0.5 can still identify strongly elevated risk.
  • Stratification preserves class shares but does not increase the number of rare examples.

6.2 Change training or change the decision rule

Class imbalance has several remedies. They act at different stages, so choose the change that addresses the actual failure: too little rare-class influence during fitting, too little local data, or a cutoff that misses useful cases.

Give rare examples more training weight

Class weights multiply each example's loss. Scikit-learn's class_weight="balanced" uses

weightk=mK mk,

where mk is the number of examples in class k. With 990 legitimate and ten fraudulent payments, weights are about 0.505 and 50. Each class then contributes total weight 500. The method equalizes total class weight; it does not turn ten distinct frauds into 500 distinct observations.

Use LogisticRegression(class_weight="balanced") to request this during fitting. A moved threshold, in contrast, does not change any loss term or coefficient.

Change the training sample

Random oversampling copies rare examples, increasing their influence but risking overfitting to those few points. Random undersampling discards common-class examples, reducing training cost but losing information.

SMOTE (synthetic minority oversampling technique) creates synthetic rare-class points between existing rare examples. Choose a rare point, one of its nearby rare-class neighbors, and a random fraction λ between 0 and 1:

𝐱new=𝐱+λ(𝐱nn−𝐱).

For (2,3) and neighbor (4,7) with λ=0.25, the displacement is (2,4), one quarter is (0.5,1), and the new point is (2.5,4). The usual imbalanced-learn default considers five rare-class neighbors. Synthetic points can fall into a common-class region when classes overlap, so extra points need not mean better evidence.

Split before resampling

Resample training data only. Validation and test data keep the deployment class mix. Duplicating examples before splitting can put copies on both sides, allowing the model to encounter test evidence during fitting. SMOTE can leak information similarly through the points used to generate neighbors.

During cross-validation, fit preprocessing and resampling separately inside each training fold. Use imbalanced-learn's Pipeline to apply the sampler during fitting while leaving prediction data unresampled. Resampling an entire training set before dividing it into validation folds still leaks across those folds.

Move the threshold without refitting

Lowering a cutoff from 0.5 to 0.2 flags more positives, including both additional true rare cases and more false alarms. Choose the cutoff on representative validation data using the costs of missed events and unnecessary checks. Keep the final test data out of that decision.

Weighting and resampling change the effective class mix the model learns from. Their raw probability outputs can be inflated relative to deployment rare-event rates. If risk probabilities themselves matter, consider threshold moving on an unweighted model or recalibrating probabilities on representative data. In generative models, changing priors also changes class decisions: equalizing priors expands the formerly rare class's region compared with using its small population prior.

Key Takeaways

  • Balanced class weights equalize total weight across classes.
  • Oversampling copies rare examples; undersampling removes common examples.
  • SMOTE interpolates between rare-class neighbors and can add noise in overlap regions.
  • Split first and resample within each training fold only.
  • Lowering a threshold changes decisions without changing the fitted model.
  • Choose the cutoff on representative validation data.
  • Rebalanced training can change probability meaning relative to real class rates.

Classification in Machine Learning examples

6 Walkthroughs

1

Follow one input from features to a decision

13 steps
Build a fault prediction, interpret its odds, and move its decision boundary.
  1. 1
    IntroductionGive a yes-or-no prediction a meaning

    A fault detector has two jobs: estimate how likely a fault is, then decide whether to flag the case. Those jobs use related but different outputs.

    Follow a model from its target label through a weighted score and a sigmoid probability. Then change the decision rule and see which parts of the prediction actually change.

  2. 2
    ExplanationDefine the event to detect

    Code “fault” as 1 and “normal” as 0. The positive class is the event the model should detect; it need not be a desirable outcome.

    A training row contains measured features and one observed label. A target such as fault type is a category. A target such as remaining operating time in hours is a quantity and calls for regression.

  3. 3
    ChallengeCheck what the target means

    A system records “normal,” “loose connection,” or “worn bearing.” Each record gets exactly one label. A colleague stores them as 0, 1, and 2 and fits ordinary linear regression. What is wrong with the target interpretation?

    ---reveal---

    These are three unordered categories. Regression treats their codes as an ordered, equally spaced scale, as if “loose connection” were halfway between the other states. A multiclass classifier matches the target.

  4. 4
    ExampleCompute a score before a probability

    Use a simple fault model with score z=0.5x−2, where x is a sensor reading. For a reading of 5, multiply first: 0.5(5)=2.5. Then add the bias, giving z=0.5.

    This score is an unrestricted real value. Its sign locates the case relative to the zero-score boundary, but 0.5 here is not yet the fault probability.

  5. 5
    ExamplePass the score through the sigmoid

    Put the score 0.5 into the sigmoid:

    p^=11+e−0.5≈0.622.

    The model therefore assigns the reading a fault probability of about 0.622. At a 0.5 cutoff it is flagged. The normal-class probability is the complement, about 0.378. Keep the score and probability in separate steps so an unrestricted score is never mistaken for a probability.

  6. 6
    Key InsightA weight scales odds

    Increasing the sensor reading by one adds 0.5 to the score. Since the score is log-odds, the odds multiply by e0.5≈1.649.

    The probability increase depends on the starting reading. The sigmoid is steep near score zero and flatter at its ends, so the same reading change has a smaller probability effect when the estimate is already near 1.

  7. 7
    ChallengeRead a probability without turning it into a fraction of a case

    A well-calibrated detector assigns probability 0.7 to many new cases. What should happen among those cases, and what does this say about one case?

    ---reveal---

    Roughly 70% of those cases should be faults. Each individual case still has one observed state: fault or normal. The probability expresses uncertainty across comparable predictions, not that one machine is partly in the fault class.

  8. 8
    ExampleFind the switch point

    The model flags readings when probability is at least 0.5. That occurs exactly when its score is nonnegative.

    Solve 0.5x−2=0 to get boundary reading 4. Lower readings are on the negative side and higher readings are on the positive side. At exactly 4, probability is 0.5 and the inclusive rule flags the case.

  9. 9
    ConnectionRead the same rule in two dimensions

    With two sensor features, a score such as z=2x1+x2−6 gives the line 2x1+x2=6. The weight vector (2,1) is perpendicular to this line and points toward increasing fault scores.

    Moving along the line keeps probability at 0.5. Moving across it in the weight-vector direction increases the probability. This gives a geometric meaning to the same score calculation.

  10. 10
    ExampleMove the cutoff to 0.7

    Return to z=0.5x−2. A probability cutoff of 0.7 requires score ln⁡(0.7/0.3)≈0.847.

    Solving 0.5x−2=0.847 gives a new boundary near 5.695. The reading of 5 still gets probability about 0.622, but it is no longer flagged. Moving the cutoff changes the decision while leaving the fitted estimate intact.

  11. 11
    TipLet feature choice determine possible shapes

    A score built from original features has a flat zero-score boundary. Squared inputs can change that shape: z=x12+x22−4 gives a circle of radius 2.

    The model is still linear in the coefficients of those squared inputs. Extra terms allow more detailed boundaries but can also fit noise, especially when classes overlap.

  12. 12
    ChallengeSeparate confidence from the class regions

    A model uses a 0.5 cutoff. Every weight and its bias are multiplied by 3. What happens to its boundary and to a point whose original score was 0.5?

    ---reveal---

    The zero-score boundary stays fixed. The point’s score becomes 1.5, so it stays positive but its probability rises from about 0.622 to about 0.818. The same class boundary can support different confidence levels.

  13. 13
    RecapKeep the three outputs distinct

    A feature vector gives a score, the sigmoid gives a probability, and the cutoff gives a decision. Weights act linearly on log-odds. Feature construction determines the shapes the model can express, while the cutoff determines which probability estimates lead to a positive decision.

2

Train a small logistic model by hand

14 steps
Calculate losses and one full-batch update, then connect the calculation to a saved pipeline.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake fitting visible
  2. 2
    ExplanationGive the observed outcome its probability
  3. 3
    ExampleAverage two different losses
  4. 4
    ChallengeRecognize a costly change
  5. 5
    ExampleStart with equal uncertainty
  6. 6
    ExampleCalculate both gradients
  7. 7
    ExampleSubtract the scaled gradients
  8. 8
    ChallengeCatch a mixed update
  9. 9
    Key InsightA falling loss need not mean bounded weights
  10. 10
    TipRead the training trace
  11. 11
    ExplanationSave the input transformation with the model
  12. 12
    ExampleRead one returned row
  13. 13
    ChallengeConnect a coefficient to a prediction
  14. 14
    RecapRead the whole fitted model
3

Compare separate models with a joint softmax

11 steps
Build multiclass decisions, compute a stable softmax, and check whether labels are exclusive.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDecide what one prediction must contain
  2. 2
    ExplanationBuild one-vs-rest training labels
  3. 3
    ExampleChoose a winner below 0.5
  4. 4
    ChallengeCount models and identify the smaller training sets
  5. 5
    ExplanationGive the classes one probability budget
  6. 6
    ExampleCalculate a simple softmax
  7. 7
    ExampleEvaluate the observed class
  8. 8
    Key InsightShift scores without shifting probabilities
  9. 9
    ConnectionSeparate exclusive classes from coexisting tags
  10. 10
    ChallengeDiagnose the wrong probability rule
  11. 11
    RecapChoose the construction from the target
4

Build and test a neighborhood vote

13 steps
Find neighbors, compare voting rules, and diagnose scaling and neighborhood-size choices.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionLet similar cases supply evidence
  2. 2
    ExplanationDefine the distance
  3. 3
    ExampleSort the stored examples
  4. 4
    ExampleCount labels for a uniform vote
  5. 5
    ExampleGive nearby points more influence
  6. 6
    ChallengeCheck what an odd neighborhood size guarantees
  7. 7
    ExplanationControl local detail with k
  8. 8
    ExampleSee a large scale dominate distance
  9. 9
    ExampleApply training-scale units
  10. 10
    TipFit the whole comparison inside each fold
  11. 11
    Key InsightMore features can weaken similarity
  12. 12
    ChallengeCombine validation with local evidence
  13. 13
    RecapInspect the neighborhood that made the prediction
5

Update class beliefs and compare model assumptions

17 steps
Compute Bayes scores, apply naive Bayes, and connect covariance assumptions to classifier choice.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionCombine frequency with feature evidence
  2. 2
    ExplanationKeep the conditioning direction straight
  3. 3
    ExampleCompute likelihood times prior
  4. 4
    ExampleNormalize across the classes
  5. 5
    ChallengeChange the prior while keeping evidence fixed
  6. 6
    ExplanationAdd a second feature through naive Bayes
  7. 7
    ExampleCombine two observed flags
  8. 8
    TipMatch the variant and handle zeros
  9. 9
    ChallengeNotice repeated evidence
  10. 10
    ExplanationReplace independent features with a shared class shape
  11. 11
    ExampleBegin at the midpoint
  12. 12
    ExampleMove the boundary with the priors
  13. 13
    ConnectionAllow separate class covariances
  14. 14
    ChallengeChoose the assumption the evidence supports
  15. 15
    ExplanationCompare how models spend their work
  16. 16
    ChallengeConnect representation, data, and serving cost
  17. 17
    RecapRead assumptions as modeling choices
6

Improve a rare-event detector without leakage

12 steps
Read a majority baseline, compare weighting and sampling, and choose a cutoff on representative data.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk what the detector actually catches
  2. 2
    ExampleCompare with doing nothing
  3. 3
    Key InsightLocate where rare cases are difficult
  4. 4
    ChallengeRead an elevated probability
  5. 5
    ExampleBalance loss contributions
  6. 6
    ExplanationCopy examples or remove examples
  7. 7
    ExampleCreate a point along a rare-class segment
  8. 8
    TipKeep sampling inside training folds
  9. 9
    ExampleChange actions while keeping probabilities
  10. 10
    ConnectionCheck what the probability now refers to
  11. 11
    ChallengeRepair the complete workflow
  12. 12
    RecapTrace each remedy to its stage

Classification in Machine Learning practice questions

50 Practice Questions in 5 sets

Set 1: Multiclass decisions and nearest-neighbor evidence10 Practice Questions

Question 1 of 10

How many pairwise binary classifiers are needed for seven classes using one-vs-one?
  1. 7
  2. 21
  3. 14
  4. 42
Show answerHide answer
Answer: B
There are seven times six ordered class pairings, but each unordered pair would be counted twice. Dividing by two gives 21 binary models. The value 42 counts both directions of the same comparison as different classifiers.

Question 2 of 10

Four one-vs-rest models return 0.18, 0.42, 0.27, and 0.33 for classes A, B, C, and D. What class is selected, and what is its probability after normalizing these outputs?
  1. B, with normalized value 0.42
  2. D, with normalized value 0.275
  3. A, with normalized value 0.15
  4. B, with normalized value 0.35
Show answerHide answer
Answer: D
B has the largest raw output, so it remains the winner after normalization. The total is 0.18+0.42+0.27+0.33=1.20, giving B the normalized value 0.42/1.20=0.35. Keeping 0.42 identifies the correct class but leaves its independent binary output unnormalized; its position below 0.5 does not prevent a winner.

Question 3 of 10

Softmax scores are (ln⁡2,0,ln⁡3). What probability does the third class receive?
  1. 0.50
  2. 0.60
  3. 0.33
  4. 0.75
Show answerHide answer
Answer: A
Exponentiating the scores gives eln⁡2=2, e0=1, and eln⁡3=3. The third class therefore receives 3/(2+1+3)=0.50. The value 0.60 divides only by the two nonzero original scores’ exponentials and drops the contribution of score zero, even though its exponential is 1.

Question 4 of 10

A softmax model has scores (1002,1000,999). The second class is true. What stable score triple can be used, and what is its cross-entropy loss?
  1. (2, 0, −1); loss about 1.099
  2. (0, −2, −3); loss about 0.170
  3. (0, −2, −3); loss about 2.170
  4. (−2, 0, 1); loss about 1.349
Show answerHide answer
Answer: C
Subtracting the largest score gives (0,−2,−3), preserving probabilities without huge exponentials. The second class receives e−2/(1+e−2+e−3)≈0.114, so its loss is about 2.170. A loss of 0.170 uses the winning first class’s probability even though the second class is true.

Question 5 of 10

A document can be tagged both “research” and “policy.” What output structure suits these labels?
  1. One sigmoid probability per label
  2. One shared softmax over labels
  3. One continuous score for label order
  4. One binary output for all labels
Show answerHide answer
Answer: A
The labels can coexist, so each needs a separate probability and decision. A shared softmax would force the labels to compete for a total probability of 1, which models mutually exclusive classes instead of simultaneous tags.

Question 6 of 10

A query is at (0, 0). Training points are A = (0, 2), red; B = (2, 1), blue; C = (3, 0), blue; D = (0, 5), red. With three uniform Euclidean neighbors, what is the blue probability?
  1. 1/3
  2. 2/3
  3. 1/2
  4. 3/4
Show answerHide answer
Answer: B
The distances are 2, about 2.236, 3, and 5, so A, B, and C are selected. Two of these three are blue, giving probability 2/3. Counting both red points would include D even though it lies outside the selected neighborhood.

Question 7 of 10

At query (0, 0), training points are red at (1, 0), blue at (0, 3), blue at (4, 0), and red at (0, 8). For three inverse-distance-weighted neighbors, what class and blue probability result?
  1. Blue, with blue probability 2/3
  2. Red, with blue probability 7/31
  3. Red, with blue probability 7/19
  4. Blue, with blue probability 12/19
Show answerHide answer
Answer: C
The selected distances are 1, 3, and 4; the fourth point does not vote. Red receives weight 1, while blue receives 1/3+1/4=7/12, giving blue probability (7/12)/(1+7/12)=7/19 and a red prediction. The fraction 2/3 counts labels without applying the requested distance weights.

Question 8 of 10

A binary kNN model uses nine equally weighted neighbors. What possible blue probability is closest to 0.5?
  1. Exactly 1/2
  2. 3/9 or 6/9
  3. Exactly 1/9
  4. 4/9 or 5/9
Show answerHide answer
Answer: D
Uniform kNN probabilities come in steps of one ninth. Four or five blue neighbors give the values closest to one half, and neither permits a binary vote tie. A probability of exactly 0.5 would require four and a half blue neighbors.

Question 9 of 10

A one-neighbor model makes no training mistakes, while seven neighbors perform better on held-out validation cases. What value should be preferred from this evidence?
  1. One, using the training result
  2. One, because local fits are exact
  3. Seven, because odd k removes noise
  4. Seven, using the validation result
Show answerHide answer
Answer: D
Validation cases measure performance on examples not used for fitting, so their result supports seven neighbors. Zero training error at one neighbor is weak evidence because each training example can select itself. An odd neighborhood size prevents binary uniform ties, not noise.

Question 10 of 10

A query is (10, 1000). Same-scale training points are P = (11, 1300) and Q = (14, 1050). Training standard deviations are 2 and 500. Which point is nearest before and after standardization?
  1. Raw: P; standardized: Q
  2. Raw: Q; standardized: Q
  3. Raw: Q; standardized: P
  4. Raw: P; standardized: P
Show answerHide answer
Answer: C
Raw distances are about 300 to P and 50 to Q, so Q is nearer. Standardized differences are (0.5,0.6) for P and (2,0.1) for Q, giving distances about 0.781 and 2.002, so P becomes nearer. Keeping Q after scaling overlooks how division by each training spread changes the relative coordinate contributions.
Set 2: Logistic predictions, boundaries, and training10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A sorting system predicts “paper,” “glass,” or “metal.” What kind of supervised task is this?
  1. Continuous regression
  2. Binary classification
  3. Multiclass classification
  4. Multilabel classification
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A logistic model gives score z=−ln⁡3. What positive-class probability does it assign?
  1. 0.25
  2. 0.75
  3. 0.50
  4. 0.33
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A logistic feature has weight ln⁡2. Its value rises by 2 units while other features stay fixed. Starting odds are 3. What are the new odds?
  1. 6
  2. 5
  3. 9
  4. 12
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A model uses z=2x1−x2−4 and predicts positive when probability is at least 0.5. What class does it assign to (3,1)?
  1. Class 0, with score −1
  2. Class 1, with score 1
  3. Class 1, with score 3
  4. Class 0, with score 1
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A model has score z=x−2. All parameters are multiplied by 2, and the cutoff is raised to 0.8. What is the new boundary and positive side? Use ln⁡4≈1.386.
  1. Boundary about 3.386; positive at or above it
  2. Boundary about 2.693; positive at or above it
  3. Boundary about 2.693; positive at or below it
  4. Boundary about 1.307; positive at or above it
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A negative example receives positive-class probability 0.4. What probability enters its negative logarithm in log loss?
  1. 0.4
  2. 0.5
  3. 0.0
  4. 0.6
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Two examples have labels 1 and 0. Model R gives positive probabilities 0.8 and 0.2; model S gives 0.6 and 0.4. How do their average log losses compare?
  1. R: about 0.223; S: about 0.511
  2. R: about 0.511; S: about 0.223
  3. R: about 0.916; S: about 0.714
  4. R: about 0.447; S: about 1.022
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

For two training rows, feature values are 1 and 5 and labels are 0 and 1. Starting weight and bias are both zero. After one gradient-descent step with learning rate 0.2, what are the new parameters?
  1. Weight −0.2; bias 0
  2. Weight 0.4; bias 0
  3. Weight 0.2; bias 0
  4. Weight 0.2; bias 0.1
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Two rows have feature values 0 and 2 and labels 1 and 0. Start with weight 0 and bias ln⁡3. What are the parameters after one full-batch gradient step with learning rate 0.2?
  1. Weight −0.15; bias ln⁡3 − 0.05
  2. Weight −0.30; bias ln⁡3 − 0.10
  3. Weight −0.15; bias ln⁡3 + 0.05
  4. Weight 0.15; bias ln⁡3 − 0.05
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A fitted classifier has classes_ = ["accept", "reject"] and returns predict_proba row [0.28, 0.72]. “Reject” is the event of interest. What decision follows from an inclusive cutoff of 0.65?
  1. Accept, using probability 0.72
  2. Reject, using probability 0.72
  3. Reject, using probability 0.28
  4. Accept, using probability 0.28
Show answerHide answer

Save this lesson to see this answer.

Set 3: Bayes probabilities and classifier choices10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

In a warehouse, 10% of parts are damaged. A mark appears on 60% of damaged parts and 5% of intact parts. What is the probability a marked part is damaged?
  1. 0.60
  2. 0.10
  3. 12/13, about 0.923
  4. 4/7, about 0.571
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A generative detector has likelihoods 0.4 for a feature pattern in faults and 0.1 in normal cases. Faults were half of its sampled training data but are 5% of deployment cases. With deployment priors and a 0.5 cutoff, what happens to a case with this pattern?
  1. Fault; fault posterior about 0.800
  2. Normal; fault posterior about 0.174
  3. Normal; fault posterior about 0.050
  4. Fault; fault posterior about 0.667
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A text model uses the number of occurrences of each word as its features. What naive Bayes variant matches this representation?
  1. Multinomial naive Bayes
  2. Bernoulli naive Bayes
  3. Gaussian naive Bayes
  4. Shared-covariance LDA
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A class has 120 word occurrences and a vocabulary of 30 words. A word occurs twice in that class. What is its add-one-smoothed probability?
  1. 3/121, about 0.025
  2. 3/150 = 0.02
  3. 2/150, about 0.013
  4. 2/120, about 0.017
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A two-feature Bernoulli naive Bayes model has equal priors. Class A has feature-presence probabilities (0.8, 0.7); class B has (0.4, 0.2). For presence of the first feature and absence of the second, what posterior and class result?
  1. A posterior 7/8; predict A
  2. A posterior 3/7; predict A
  3. A posterior 3/7; predict B
  4. A posterior 3/11; predict B
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What feature-distribution assumption distinguishes LDA from QDA?
  1. LDA shares covariance across classes
  2. LDA shares every class mean
  3. LDA allows only two classes
  4. LDA removes class priors entirely
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Two one-dimensional normal classes have means 0 and 4 and common variance 4. Prior A is 0.75 and prior B is 0.25. Where is the LDA boundary, and what class does x = 2.5 receive? Use ln⁡3≈1.099.
  1. Boundary 2; class B
  2. Boundary about 0.901; class B
  3. Boundary about 3.099; class B
  4. Boundary about 3.099; class A
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An LDA model has five classes and three input features. What is the largest possible number of discriminant projection directions?
  1. 2
  2. 4
  3. 3
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A team must classify many new records quickly after training. It has a fixed, modest feature set and a roughly straight boundary. Why is logistic regression a sensible baseline against brute-force kNN?
  1. Training never requires iterative fitting
  2. Prediction uses fixed coefficients per record
  3. Its probabilities are always perfectly calibrated
  4. Its boundary adapts locally to every stored point
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

For three roughly normal classes with ten features, LDA and QDA have similar validation results on a small sample. What covariance comparison supports choosing LDA?
  1. LDA fits 10 entries; QDA fits 30
  2. LDA fits 55 entries; QDA fits 110
  3. LDA fits 100 entries; QDA fits 300
  4. LDA fits 55 entries; QDA fits 165
Show answerHide answer

Save this lesson to see this answer.

Set 4: Rare events and reliable training workflows10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Only 12 of 600 alerts concern a real fault. What accuracy does an always-“no fault” classifier achieve?
  1. 98%
  2. 2%
  3. 96%
  4. 99%
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A population has 2% faulty cases. A model assigns a new case fault probability 0.12. How should this estimate be read?
  1. Twelve times the background rate, below 0.5
  2. Six times the background rate, above 0.5
  3. A 12% increase over the background rate
  4. Six times the background rate, below 0.5
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A binary training set has 180 common and 20 rare examples. Under balanced class weighting, what weight does each rare example receive?
  1. 9
  2. 10
  3. 5
  4. 0.556
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A team oversamples its complete data, then splits it into training and test subsets and reports a large gain in rare-case detection. What workflow is needed to judge the gain reliably?
  1. Split original data; resample training and test to equal shares
  2. Resample original data; split; remove duplicate training rows
  3. Split original data; resample training; retain original test mix
  4. Resample original data; split; lower the test decision cutoff
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A training pipeline uses standardized SMOTE between rare points (1, 2) and (5, 6). For interpolation fraction 0.75, what synthetic point is formed, and in which cross-validation subset may it be generated?
  1. (2, 3), within a training fold
  2. (4, 5), within a training fold
  3. (4, 5), before dividing into folds
  4. (4, 5), within a validation fold
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A fitted unweighted model uses a 0.5 cutoff. Without refitting, the team lowers it to 0.25. What changes?
  1. More positive decisions; probabilities stay fixed
  2. More positive decisions; probabilities increase
  3. Fewer positive decisions; probabilities stay fixed
  4. Fewer positive decisions; coefficients shrink
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A scaler and classifier were fitted as one pipeline. A developer then fits a fresh scaler on each incoming batch and sends those values directly to the saved classifier. Why can identical records receive inconsistent predictions across batches?
  1. The saved classifier updates its weights on each new batch
  2. New scaling changes the saved classifier’s class-column order
  3. Batch statistics change the classifier’s original training labels
  4. Batch statistics change the classifier’s input coordinates
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Two candidate kNN models use the same scaled sensor features. With k = 1, a lone mislabeled point creates a small opposite-class region; with k = 11, a genuine small fault cluster disappears into common neighbors. What does this show about selecting k?
  1. Choose k = 1 because preserving all local regions is best
  2. Validation must balance local noise against loss of small clusters
  3. Choose k = 11 because smoothing always improves new predictions
  4. Training error alone identifies which local regions are genuine
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A classifier uses z=x12+x22−9 with an inclusive 0.5 probability cutoff. What class does point (1,2) receive?
  1. Class 1, inside the radius-3 circle
  2. Class 0, outside the radius-3 circle
  3. Class 0, inside the radius-3 circle
  4. Class 1, outside the radius-3 circle
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An unpenalized logistic fit has zero training classification errors, keeps reducing log loss, and develops rapidly growing coefficient magnitudes. How should this behavior be interpreted and addressed?
  1. Separation can prevent a finite optimum; use a penalty
  2. Convexity rules out separation; reduce feature count
  3. Zero class errors guarantee convergence; keep the fit
  4. Falling loss proves finite weights; raise the iteration limit
Show answerHide answer

Save this lesson to see this answer.

Set 5: Connect probabilities, model assumptions, and decisions10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A three-class classifier gives probabilities 0.15, 0.25, and 0.60. The first class is true. What probability determines its cross-entropy loss?
  1. 0.25
  2. 0.15
  3. 0.60
  4. 0.85
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A logistic model gives probability 0.2. One feature increases by an amount that adds ln⁡4 to the score. What is the new probability?
  1. 0.8
  2. 0.4
  3. 0.5
  4. 0.6
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A balanced five-class data set is turned into one-vs-rest problems. How many models are fitted, and what positive share does each model see?
  1. 10 models; 20% positive
  2. 5 models; 50% positive
  3. 10 models; 50% positive
  4. 5 models; 20% positive
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A three-class softmax model has scores (x,0,−x). A new point has x=ln⁡2 and the third class is observed. What class is predicted, and what is the loss?
  1. First class; loss ln⁡7
  2. First class; loss ln⁡(7/4)
  3. Third class; loss ln⁡7
  4. Second class; loss ln⁡(7/2)
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A query has neighbors red at (1, 0), blue at (0, 2), and blue at (3, 0), measured from (0, 0). What happens when a three-neighbor vote changes from uniform to inverse-distance weighting?
  1. Uniform blue; weighted blue, blue probability 2/3
  2. Uniform red; weighted blue, blue probability 6/11
  3. Uniform blue; weighted red, blue probability 1/3
  4. Uniform blue; weighted red, blue probability 5/11
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A feature pattern has likelihood 0.6 in class A and 0.2 in B. With equal priors, A wins. If A’s deployment prior is 0.1 and B’s is 0.9, what posterior and decision result?
  1. A posterior 0.75; predict A
  2. A posterior 0.25; predict B
  3. A posterior 0.10; predict B
  4. A posterior 0.60; predict A
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A naive Bayes classifier observes two identical binary features that are copies of one flag. Within class A each presence probability is 0.8; within B each is 0.2; priors are equal. Both flags are present. What does the naive calculation produce, and why is it suspect?
  1. A posterior 16/17; the same evidence is counted twice
  2. A posterior 4/5; the same evidence is counted twice
  3. A posterior 16/17; two independent flags add evidence
  4. A posterior 4/5; feature dependence is already removed
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Two equal-variance LDA classes have means 1 and 7 and priors 0.9 and 0.1. Their variance is 3. What boundary and class for x = 4.5 result? Use ln 9 ≈ 2.197.
  1. Boundary 4; higher-mean class
  2. Boundary about 2.901; higher-mean class
  3. Boundary about 5.099; lower-mean class
  4. Boundary about 5.099; higher-mean class
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A deployment population is 1% positive. A generative model fitted with balanced priors returns positive posterior 0.8 for a feature pattern. Keeping its likelihoods fixed, what posterior follows when deployment priors replace the balanced priors?
  1. 0.8
  2. 4/103, about 0.039
  3. 1/25, exactly 0.04
  4. 4/99, about 0.0404
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A team oversamples once, then runs cross-validation on that expanded training table, choosing k and a cutoff from those folds. A separate untouched test set remains available. What repair best supports trustworthy selection?
  1. Keep the folds; remove duplicate rows within each validation fold
  2. Use the untouched test set to choose both k and the cutoff
  3. Rebalance every validation fold to match its training fold
  4. Cross-validate original rows with sampling inside training folds
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

80 Key Terms, each with its definition

A

Average cost
The average cost is the arithmetic mean of individual training losses, used as an objective when fitting model parameters.
For four binary examples, the average cost adds their four log losses and divides the result by four.

B

Background event rate
The background event rate is the overall frequency of the positive class in the population before inspecting one case’s features.
A 0.15 fraud estimate is fifteen times a background event rate of 0.01, despite being below 0.5.
Baseline model
A baseline model is a simple initial predictor used as a reference when deciding whether a more complex method is worthwhile.
A logistic baseline model provides a useful first comparison before trying a flexible kNN boundary.
Bernoulli naive Bayes
Bernoulli naive Bayes models binary indicators and includes evidence from features that are absent as well as those present.
Bernoulli naive Bayes uses whether a vocabulary word appears at least once, not its repetition count.
Bias–variance tradeoff
The bias–variance tradeoff balances a model’s systematic limitations against its sensitivity to which training examples it receives.
In kNN, increasing k usually shifts the bias–variance tradeoff toward higher bias and lower variance.
Binary classification
Binary classification is a prediction task with two possible target classes, commonly represented by labels 0 and 1.
A binary classification model predicts whether a component is “working” or “failed.”

C

Calibration
Calibration is agreement between predicted probabilities and observed event shares across many cases receiving similar estimates.
Good calibration means about 80% positives among many examples assigned probabilities near 0.8.
Class imbalance
Class imbalance is a large difference in class frequencies, leaving one target category much rarer than another in the data.
A payment set with ten frauds among 1,000 payments has strong class imbalance.
Class label
A class label identifies the category assigned to a training example or predicted for a new example by a classifier.
“Technical” is the class label attached to a ticket asking for help with a software fault.
Class mean
A class mean is the average feature value or feature vector among the training observations assigned to one class.
LDA estimates a class mean for each label while pooling information to estimate one covariance matrix.
Class order
Class order is the ordering of labels in a fitted classifier’s classes_ attribute, matching the columns returned by predict_proba.
Checking class order avoids reading a negative-class probability as the probability of a fault.
Class weight
A class weight multiplies the training loss of each example in one class, changing how much that class influences fitting.
Balanced class weights give each fraud much more influence when fraud examples are rare.
Classification
Classification is supervised learning that predicts a category from features of an example with an unknown class label.
A classification model assigns a new support ticket to “billing,” “technical,” or “account.”
Conditional independence
Conditional independence means features behave independently once the class is fixed, even if they are related in the full population.
Naive Bayes assumes conditional independence of word indicators within spam and within non-spam.
Convergence
Convergence is the optimizer reaching its stopping criterion after sufficient progress in reducing the fitting objective.
A convergence warning suggests checking feature scaling or increasing max_iter before using the fit.
Convex objective
A convex objective has no local minimum that is worse than a global one, although a finite minimizing point need not exist.
Logistic log loss is a convex objective in the coefficients, unlike squared error after a sigmoid.
Covariance matrix
A covariance matrix records feature variances on its diagonal and pairwise covariances elsewhere, summarizing spread and co-variation.
A shared covariance matrix gives every LDA class the same spread and feature-correlation structure.
Cross-entropy
Cross-entropy measures multiclass prediction loss as the negative logarithm of the probability assigned to the observed class.
A true technical ticket with predicted technical probability about 0.245 has cross-entropy about 1.408.
Curse of dimensionality
The curse of dimensionality is the sparsity and loss of useful distance contrast that can develop as feature count grows.
The curse of dimensionality can make text-vector neighbors uninformative even after feature scaling.

D

Data leakage
Data leakage occurs when fitting or model selection uses information that should be unavailable from the held-out evaluation examples.
Oversampling before a split causes data leakage when copies of one case enter both training and test data.
Decision boundary
A decision boundary is the set of feature-space locations where a classifier switches from one predicted class region to another.
When a model’s predicted class changes as the sum of two feature values passes 3, its decision boundary is the line where they sum to 3.
Decision threshold
A decision threshold is the probability cutoff used to turn a model’s estimate into a predicted class or action.
Raising the decision threshold from 0.5 to 0.8 reduces the number of cases flagged positive.
Discriminant projection
A discriminant projection maps features onto directions chosen using class labels to emphasize separation between classes.
An LDA discriminant projection for three classes uses at most two directions, even with many features.
Discriminative classifier
A discriminative classifier models class membership from features directly, without modeling each class’s feature distribution.
Logistic regression is a discriminative classifier that estimates positive probability from a linear score.
Distance weighting
Distance weighting gives closer selected neighbors more influence, commonly using inverse distance as each neighbor’s vote weight.
With distance weighting, the blue probability is its total neighbor weight divided by all selected weight.

E

Engineered feature
An engineered feature is an input constructed from original measurements, such as a squared value or a product of inputs.
A squared engineered feature lets logistic regression form a curved boundary in original coordinates.
Euclidean distance
Euclidean distance is straight-line distance, computed as the square root of the sum of squared coordinate differences.
Between points (3, 3) and (2, 4), Euclidean distance is about 1.414 feature-space units.

F

Feature vector
A feature vector is an ordered collection of input measurements describing one example presented to a model.
The feature vector for a machine part can contain operating temperature and vibration measurements.

G

Gaussian naive Bayes
Gaussian naive Bayes fits a separate normal distribution for each continuous feature in each class, with class-specific variances.
Gaussian naive Bayes can model temperature and vibration separately within each machine-state class.
Generative classifier
A generative classifier models feature distributions within classes and class priors, then uses Bayes’ theorem to obtain posteriors.
A generative classifier can give common classes larger decision regions through their larger priors.
Gradient
A gradient is the vector of partial derivatives describing how a cost changes locally as each model parameter changes.
The logistic weight gradient averages prediction error times the corresponding feature value.
Gradient descent
Gradient descent repeatedly subtracts a learning-rate-scaled gradient from the parameters to reduce a training objective.
For a model starting with all parameters at 0, one gradient descent step changes a weight from 0 to 0.05 while leaving the bias at 0.

I

Interpretability
Interpretability is the ability to connect a model’s behavior to understandable evidence, parameters, or examples behind a prediction.
Showing a kNN query’s neighbors gives interpretability through the cases that supplied its votes.
Irrelevant feature
An irrelevant feature is an input that adds no useful class information and can obscure similarity when included in distances.
Adding an irrelevant feature to kNN can separate otherwise similar sensor cases in the distance calculation.

K

k-nearest neighbors
k-nearest neighbors is an instance-based classifier that predicts from the labels of the selected closest training examples.
A k-nearest neighbors model can predict blue from two blue votes and one red vote near the query.

L

Laplace smoothing
Laplace smoothing adds one to every event count and adds the number of possible events to the total before estimating probabilities.
Laplace smoothing gives an unseen word a small nonzero likelihood instead of erasing a class score.
Lazy learning
Lazy learning defers most modeling work until a prediction is requested, keeping training examples available for local comparisons.
kNN is lazy learning: fitting stores data and may build an index, while prediction finds neighbors.
Learning rate
The learning rate is the positive multiplier controlling the size of each parameter change in a gradient-descent update.
An excessive learning rate can make the logistic training cost jump upward or oscillate.
Likelihood
A likelihood describes the probability or density of observed features within a specified class, as used in a generative classifier.
The likelihood of “prize” within spam is distinct from the probability that an email with “prize” is spam.
Linear discriminant analysis
Linear discriminant analysis models normal classes with different means and one shared covariance, producing flat class boundaries.
Linear discriminant analysis places its equal-prior, equal-variance boundary midway between two means.
Linear score
A linear score is a weighted sum of the input features plus a bias, evaluated before converting the result to a probability.
When an exam model’s linear score is zero after four hours of study, it predicts a pass probability of 0.5 for that student.
Log loss
Log loss is the negative natural logarithm of the probability a model assigns to the true class of an observed example.
A positive example predicted at 0.1 receives log loss about 2.303, a large penalty for low confidence.
Log-odds
Log-odds are the natural logarithm of the odds and equal the linear score in a logistic regression model.
A feature weight of 0.8 adds 0.8 to log-odds for a one-unit increase with other features fixed.
Logistic regression
Logistic regression is a classifier that converts a linear feature score to a class probability using the sigmoid function.
Binary logistic regression predicts a fault probability before a threshold turns it into a class decision.

M

Majority-class baseline
A majority-class baseline predicts the most common class for every example, providing a simple reference for an imbalanced task.
The majority-class baseline is 99% accurate when fraud is 1% of payments, yet it detects no fraud.
Manhattan distance
Manhattan distance is the sum of absolute coordinate differences, measuring total movement parallel to the feature axes.
Between points (3, 3) and (2, 4), Manhattan distance is 2, one unit along each axis.
Maximum likelihood
Maximum likelihood fits parameters by making the observed labels as probable as possible under the model’s probability rule.
For binary logistic regression, maximum likelihood fitting is equivalent to minimizing log loss.
Multiclass classification
Multiclass classification assigns each example exactly one label from three or more possible categories with no required ordering.
Choosing one of four issue categories for a ticket is multiclass classification, even with integer labels.
Multilabel classification
Multilabel classification permits several labels to apply to one example, with a separate probability decision for each label.
Tagging one article as both “sports” and “business” is multilabel classification, not one softmax choice.
Multinomial naive Bayes
Multinomial naive Bayes models counted events through class-specific event probabilities, making it useful for word-count features.
Multinomial naive Bayes scores a review from its word occurrence counts and the learned class word rates.

N

Naive Bayes
Naive Bayes is a generative classifier that factors a class’s feature likelihood into a product under conditional independence.
Naive Bayes multiplies separate word likelihoods and a class prior to score a document.
Neighborhood size
Neighborhood size is the number of selected neighbors, k, that contribute to one kNN prediction and control its local smoothness.
Increasing neighborhood size makes a kNN prediction less sensitive to the label of one nearby point.
Nonparametric model
A nonparametric model can increase its stored representation with the amount of training data, as kNN does by retaining examples.
kNN is a nonparametric model because additional training examples enlarge its stored reference set.
Normalization
Normalization divides nonnegative class scores by their total so the resulting class values form a probability distribution.
Normalization makes separate one-vs-rest probabilities sum to 1 without jointly refitting their models.
Numerical underflow
Numerical underflow occurs when a positive number is too small for a computer’s representation and is rounded to zero.
Adding log-likelihoods prevents numerical underflow from multiplying many small word probabilities.

O

Odds
Odds express an event’s probability divided by its complement, comparing the chance of the event with the chance of its absence.
A probability of 0.75 gives odds of 3, meaning three expected positives for each expected negative.
One-hot label
A one-hot label is a class indicator vector with 1 in the observed class’s position and 0 in every other position.
For three ticket classes, the one-hot label for the second class is a vector with entries 0, 1, and 0.
One-vs-one
One-vs-one trains a binary classifier for every distinct pair of classes and combines pairwise results through votes.
A ten-class one-vs-one system needs 45 binary models, each fitted on only its two relevant classes.
One-vs-rest
One-vs-rest trains a binary classifier for each class against all remaining classes and selects the class with the largest output.
Three one-vs-rest ticket models can return probabilities whose total exceeds 1 before normalization.
Overfitting
Overfitting occurs when a model follows details of its training examples that do not support good predictions on new data.
Adding polynomial terms can cause overfitting by bending a boundary around noisy training labels.

P

Parametric model
A parametric model represents training data with a fixed-size parameter collection for a specified feature count and class set.
Logistic regression is a parametric model whose coefficient count stays fixed as training rows increase.
Perfect separation
Perfect separation occurs when a decision boundary places every training example on the side corresponding to its class.
With perfect separation, unpenalized logistic log loss keeps decreasing as separating weights grow.
Pipeline
A pipeline combines fitted preprocessing and a classifier so training and future inputs follow the same sequence of transformations.
A pipeline fits StandardScaler on the training rows before fitting the logistic classifier.
Positive class
The positive class is the category coded 1 that a binary classifier is designed to detect, including an unwanted event.
In a machine-failure detector, the positive class is “failed,” even though failure is undesirable.
Posterior
A posterior is the probability of a class after combining the observed feature evidence with the prior through Bayes’ theorem.
In an email filter with a spam prior of 0.2, the word “prize” raises an email’s spam posterior to about 0.789.
Prior
A prior is the class probability before the current example’s feature evidence is considered, often estimated from class shares.
A spam prior of 0.2 describes the email population before inspecting whether “prize” occurs.

Q

Quadratic discriminant analysis
Quadratic discriminant analysis models normal classes with separate covariance matrices, allowing curved decision boundaries.
Quadratic discriminant analysis can fit unequal class spreads but needs more data for its extra parameters.

R

Random oversampling
Random oversampling copies examples from the rare class to increase its representation in training without adding distinct observations.
Random oversampling can overfit the few original fraud cases when their copies appear many times.
Random undersampling
Random undersampling removes selected common-class examples to reduce class imbalance and training size, discarding some information.
Random undersampling speeds fitting by retaining fewer legitimate payments from the training set.
Regularization
Regularization adds a penalty that discourages large fitted weights and can keep logistic coefficients finite on separable data.
Stronger regularization in scikit-learn logistic regression is requested with a smaller value of C.

S

Score-shift invariance
Score-shift invariance means that adding one common constant to all softmax scores leaves every resulting probability unchanged.
Score-shift invariance lets software subtract the largest score before evaluating exponentials.
Sigmoid function
The sigmoid function maps any finite real score to a probability strictly between 0 and 1, with a zero score mapping to 0.5.
A sigmoid function turns score 2 into probability about 0.881 and score −2 into about 0.119.
SMOTE
SMOTE, short for synthetic minority oversampling technique, creates rare-class examples along segments between rare-class neighbors.
SMOTE can add noisy points when a segment between rare cases passes through a common-class region.
Softmax regression
Softmax regression fits one score per class and jointly converts the scores into probabilities for mutually exclusive classes.
Default multiclass logistic regression uses softmax regression to predict one support-ticket category.
Standardization
Standardization subtracts a feature’s training mean and divides by its training standard deviation to express comparable scales.
After standardization, a one-unit feature change represents one training standard deviation.
Stratified split
A stratified split divides labeled data while keeping each class’s proportion approximately similar across the resulting subsets.
A stratified split helps distribute a small number of fraud examples between training and test data.

T

Threshold moving
Threshold moving changes the probability cutoff used for decisions while keeping the trained model and its estimated probabilities fixed.
Threshold moving from 0.5 to 0.2 sends more payments for review and usually increases false alarms.

U

Uniform voting
Uniform voting gives each selected neighbor one equal vote and estimates a class probability as its share of the neighbors.
With uniform voting, three blue labels among five neighbors give a blue probability of 0.6.

V

Validation data
Validation data are held-out examples used to compare settings and models before making a final assessment on separate test data.
Use validation data to choose k instead of selecting the model with the lowest training error.

W

Weight vector
A weight vector collects the coefficients of a linear score and points perpendicular to its zero-score decision boundary.
The weight vector points into the class-1 side of a logistic boundary at the 0.5 cutoff.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started