- Learn
- Computer Science & IT
- Data Science & AI
- Machine Learning
- Classification in Machine Learning
Classification in Machine Learning: Logistic Regression, KNN
IntermediateLesson 3 of 9 in Machine Learning Course
What you will learn
- 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 shortTell 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 functionCompute logistic regression predictions, connect probabilities with odds and log-odds, and read what a weight does to a prediction.
- Draw and interpret decision boundariesLocate the boundary where predictions switch class, move it by changing the threshold, and bend it with engineered features.
- Recognize classification tasks and why linear regression falls short
- 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 lossCompute 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 descentApply 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-learnFit a logistic regression model in Python, get probabilities and classes with any threshold, and read the fitted weights with care.
- Measure prediction quality with log loss
- 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-oneBuild multiclass classifiers from several binary ones, predict with them, and know their costs and quirks.
- Predict class probabilities with softmax regressionCompute softmax probabilities and the cross-entropy loss, and choose correctly between multiclass and multilabel set-ups.
- Combine binary classifiers with one-vs-rest and one-vs-one
- 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 neighborsMeasure distances, find the k nearest training examples, and turn their votes into a class and a probability.
- Choose k and prepare features for kNNPick the number of neighbors with validation data, scale the features so that each one counts fairly, and recognize when kNN struggles.
- Predict by a vote of the nearest neighbors
- 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' theoremContrast generative and discriminative models, and compute posterior class probabilities from priors and likelihoods.
- Classify with naive BayesApply the naive independence assumption, compute a prediction by hand, handle unseen words with smoothing, and know the main variants.
- Understand linear and quadratic discriminant analysisExplain 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 taskWeigh logistic regression, k-nearest neighbors, naive Bayes and discriminant analysis by boundary shape, data needs, speed, probabilities and interpretability.
- Build a classifier from Bayes' theorem
- 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 effectsSpot 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 thresholdsApply class weights, oversampling, undersampling, SMOTE and threshold moving, and keep validation and test data untouched.
- Recognize class imbalance and its effects
Classification in Machine Learning study guide
1From 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 and a target label . Features might include operating temperature in °C and vibration measured by a sensor. A training set contains 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 . This is a probability for the positive class given the features. The negative-class probability is .
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 , calculate
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 it gives 0.5. Large positive scores approach probability 1; large negative scores approach 0. Its symmetry gives , so scores 2 and −2 give about 0.881 and 0.119.
Consider the exam-pass model , where 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:
For a logistic model, the log-odds equal the score . 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 . 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 .” The sigmoid reaches 0.5 exactly at score 0, so the boundary satisfies
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 . At the score is 1, giving probability about 0.731 and class 1. At the score is −1, giving about 0.269 and class 0. At 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 . 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 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 , classify as positive when
At , the needed score is about 1.386. The example's boundary moves to , shrinking the positive region. At , it moves to , 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 . Its 0.5 boundary is the unit circle, . 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.
2Fit 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 . For a negative label it is . Take the negative natural logarithm of that probability:
When , this reduces to . When , it reduces to . 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:
For labels and predictions , 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 would penalize the wrong probability; use .
Always predicting 0.5 gives loss 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 . The gradients are
Then use learning rate :
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:
The bias gradient is the mean error, which is 0. Thus the new weight is 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 . 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.
3Choose 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 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 marks examples of class 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
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.
| Construction | Binary models | Training data for one model | Prediction |
|---|---|---|---|
| One-vs-rest | All examples, with one positive class | Highest class score | |
| One-vs-one | Only the two classes in that pair | Most 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 . The scores become one probability distribution over the possible labels.
Normalize exponentials, not scores
The probability of class is
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 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 gives the same distribution as .
Software uses this property to prevent overflow: subtract the largest score before exponentiating. The original example can be evaluated as . The largest exponential is then 1, without changing any probability.
With two classes, the probability of class 1 becomes
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 . 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 , so 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.
4Predict 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 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:
Manhattan distance adds absolute changes along the axes, . Between and , the Euclidean distance is 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 , consider these stored examples:
| Point | Coordinates | Class | Euclidean distance |
|---|---|---|---|
| D | red | 1 | |
| B | blue | about 1.414 | |
| C | blue | about 1.414 | |
| E | blue | 2 | |
| F | red | about 2.236 | |
| A | red | about 2.828 |
With , only D votes, so the prediction is red. With , D, B, and C vote: two blue and one red, so blue. With , 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 , blue has probability 0.6 and red 0.4. These estimates come in multiples of ; they describe the neighborhood vote, not a fitted sigmoid.
With weights="distance", a neighbor at positive distance receives weight . 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 . Red receives about 0.414. Counting two blue neighbors out of three would ignore the weighting rule.
For binary equal voting, odd 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 follows local detail. At , one noisy label can create its own region: low bias but high variance. A larger 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 for P and 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 .
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.
5Use 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 directly. A generative model estimates a feature distribution within each class, , and a class prior, . It then combines them:
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:
The total chance of seeing the word is 0.076. Normalizing gives
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
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:
The prediction is not spam. The posterior spam probability is . “Prize” favors spam, but the combined feature evidence and prior favor non-spam.
Match the variant to the inputs
| Variant | Feature model | Typical input |
|---|---|---|
| Gaussian naive Bayes | A normal distribution per feature in each class | Continuous measurements |
| Multinomial naive Bayes | Class-specific probabilities for counted events | Word counts |
| Bernoulli naive Bayes | Present-or-absent features | Binary 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:
An unseen word among 1,000 class word occurrences with a 5,000-word vocabulary gets probability . 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
With priors 0.8 for A and 0.2 for B, this gives . 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.
| Method | What it assumes about feature distributions | Boundary on original features |
|---|---|---|
| LDA | Normal classes with shared covariance | Flat |
| QDA | Normal classes with separate covariances | Quadratic |
| Logistic regression | No class-conditional normality assumption | Flat |
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 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
| Model | Boundary on original inputs | What fitting keeps | Main practical issue |
|---|---|---|---|
| Logistic or softmax regression | Flat unless features are engineered | Weights and biases | Iterative fitting; feature representation matters |
| kNN | Flexible local shapes | Training examples and possibly an index | Distance, storage, and prediction cost |
| Naive Bayes | Depends on the variant; Gaussian can curve | Class priors and feature distributions | Conditional independence can distort probabilities |
| LDA | Flat | Means, shared covariance, priors | Shared normal class shape |
| QDA | Quadratic | Means, separate covariances, priors | More 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 ; 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.
6Learn 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
where is the number of examples in class . 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:
For and neighbor with , the displacement is , one quarter is , and the new point is . 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
1Follow one input from features to a decision
13 steps
- 1IntroductionGive 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.
- 2ExplanationDefine 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.
- 3ChallengeCheck 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.
- 4ExampleCompute a score before a probability
Use a simple fault model with score , where is a sensor reading. For a reading of 5, multiply first: . Then add the bias, giving .
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.
- 5ExamplePass the score through the sigmoid
Put the score 0.5 into the sigmoid:
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.
- 6Key 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 .
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.
- 7ChallengeRead 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.
- 8ExampleFind the switch point
The model flags readings when probability is at least 0.5. That occurs exactly when its score is nonnegative.
Solve 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.
- 9ConnectionRead the same rule in two dimensions
With two sensor features, a score such as gives the line . The weight vector 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.
- 10ExampleMove the cutoff to 0.7
Return to . A probability cutoff of 0.7 requires score .
Solving 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.
- 11TipLet feature choice determine possible shapes
A score built from original features has a flat zero-score boundary. Squared inputs can change that shape: 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.
- 12ChallengeSeparate 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.
- 13RecapKeep 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.
2Train a small logistic model by hand
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake fitting visible
- 2ExplanationGive the observed outcome its probability
- 3ExampleAverage two different losses
- 4ChallengeRecognize a costly change
- 5ExampleStart with equal uncertainty
- 6ExampleCalculate both gradients
- 7ExampleSubtract the scaled gradients
- 8ChallengeCatch a mixed update
- 9Key InsightA falling loss need not mean bounded weights
- 10TipRead the training trace
- 11ExplanationSave the input transformation with the model
- 12ExampleRead one returned row
- 13ChallengeConnect a coefficient to a prediction
- 14RecapRead the whole fitted model
3Compare separate models with a joint softmax
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDecide what one prediction must contain
- 2ExplanationBuild one-vs-rest training labels
- 3ExampleChoose a winner below 0.5
- 4ChallengeCount models and identify the smaller training sets
- 5ExplanationGive the classes one probability budget
- 6ExampleCalculate a simple softmax
- 7ExampleEvaluate the observed class
- 8Key InsightShift scores without shifting probabilities
- 9ConnectionSeparate exclusive classes from coexisting tags
- 10ChallengeDiagnose the wrong probability rule
- 11RecapChoose the construction from the target
4Build and test a neighborhood vote
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionLet similar cases supply evidence
- 2ExplanationDefine the distance
- 3ExampleSort the stored examples
- 4ExampleCount labels for a uniform vote
- 5ExampleGive nearby points more influence
- 6ChallengeCheck what an odd neighborhood size guarantees
- 7ExplanationControl local detail with k
- 8ExampleSee a large scale dominate distance
- 9ExampleApply training-scale units
- 10TipFit the whole comparison inside each fold
- 11Key InsightMore features can weaken similarity
- 12ChallengeCombine validation with local evidence
- 13RecapInspect the neighborhood that made the prediction
5Update class beliefs and compare model assumptions
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionCombine frequency with feature evidence
- 2ExplanationKeep the conditioning direction straight
- 3ExampleCompute likelihood times prior
- 4ExampleNormalize across the classes
- 5ChallengeChange the prior while keeping evidence fixed
- 6ExplanationAdd a second feature through naive Bayes
- 7ExampleCombine two observed flags
- 8TipMatch the variant and handle zeros
- 9ChallengeNotice repeated evidence
- 10ExplanationReplace independent features with a shared class shape
- 11ExampleBegin at the midpoint
- 12ExampleMove the boundary with the priors
- 13ConnectionAllow separate class covariances
- 14ChallengeChoose the assumption the evidence supports
- 15ExplanationCompare how models spend their work
- 16ChallengeConnect representation, data, and serving cost
- 17RecapRead assumptions as modeling choices
6Improve a rare-event detector without leakage
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk what the detector actually catches
- 2ExampleCompare with doing nothing
- 3Key InsightLocate where rare cases are difficult
- 4ChallengeRead an elevated probability
- 5ExampleBalance loss contributions
- 6ExplanationCopy examples or remove examples
- 7ExampleCreate a point along a rare-class segment
- 8TipKeep sampling inside training folds
- 9ExampleChange actions while keeping probabilities
- 10ConnectionCheck what the probability now refers to
- 11ChallengeRepair the complete workflow
- 12RecapTrace each remedy to its stage
Classification in Machine Learning practice questions
Set 1: Multiclass decisions and nearest-neighbor evidence10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Logistic predictions, boundaries, and training10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Average cost
B
Background event rate
Baseline model
Bernoulli naive Bayes
Bias–variance tradeoff
Binary classification
C
Calibration
Class imbalance
Class label
Class mean
Class order
classes_ attribute, matching the columns returned by predict_proba.Class weight
Classification
Conditional independence
Convergence
max_iter before using the fit.Convex objective
Covariance matrix
Cross-entropy
Curse of dimensionality
D
Data leakage
Decision boundary
Decision threshold
Discriminant projection
Discriminative classifier
Distance weighting
E
Engineered feature
Euclidean distance
F
Feature vector
G
Gaussian naive Bayes
Generative classifier
Gradient
Gradient descent
I
Interpretability
Irrelevant feature
K
k-nearest neighbors
L
Laplace smoothing
Lazy learning
Learning rate
Likelihood
Linear discriminant analysis
Linear score
Log loss
Log-odds
Logistic regression
M
Majority-class baseline
Manhattan distance
Maximum likelihood
Multiclass classification
Multilabel classification
Multinomial naive Bayes
N
Naive Bayes
Neighborhood size
Nonparametric model
Normalization
Numerical underflow
O
Odds
One-hot label
One-vs-one
One-vs-rest
Overfitting
P
Parametric model
Perfect separation
Pipeline
StandardScaler on the training rows before fitting the logistic classifier.Positive class
Posterior
Prior
Q
Quadratic discriminant analysis
R
Random oversampling
Random undersampling
Regularization
C.S
Score-shift invariance
Sigmoid function
SMOTE
Softmax regression
Standardization
Stratified split
T
Threshold moving
U
Uniform voting
V
Validation data
W
Weight vector
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.