Linear Regression


Linear Regression

Hope
Welcome back. We are moving from linear regression into the final major topic of the course: machine learning. Linear regression already gave us a useful preview. We started with experimental data, such as the weights placed on a spring and the resulting displacements, then fitted a model that could predict the displacement for a new weight.

Simon
And regression can involve different levels of model selection. Sometimes we know a linear model is appropriate and find the best-fitting line. Other times, we use validation to compare a line, a quadratic, a cubic, or a higher-order model and choose the one that fits appropriately without overfitting.

Hope
That is a natural bridge to machine learning, although machine learning is a much larger subject than we can cover in a few lectures. It connects to natural language processing, computational biology, computer vision, robotics, and many dedicated computer science subjects. The goal here is an introduction to the basic ideas behind learning algorithms, rather than a survey of the most sophisticated systems such as deep learning or convolutional neural networks.

Simon
Those basic ideas are already everywhere. Machine learning powers recommendation systems such as Netflix or Amazon suggestions, targeted advertising, handwritten-character recognition, face recognition, speech systems such as Siri, medical applications such as cancer diagnosis, drug discovery, assistive driving, financial systems, and game-playing programs. Google’s AlphaGo defeating a world-class Go player is one dramatic example, following earlier computer successes in chess.

Hope
A classic definition comes from Arthur Samuel in 1959: machine learning is the field of study that gives computers the ability to learn without being explicitly programmed. Samuel’s checkers program improved by examining its game experience and inferring changes to its strategy. The historical progression is striking: early systems played checkers, chess was later conquered, and Go became another major achievement.

Simon
There is also a provocative way to draw the boundary. You could argue that almost every computer program learns something, but the amount of learning varies enormously. Newton’s method for computing square roots can be stretched into that argument because it generalizes to roots of different powers, but the method itself was explicitly programmed. It does not learn in the richer sense we usually want.

Hope
Linear regression feels more like learning because we provide data and the computer fits a model to it. From the spring’s mass-displacement observations, it can infer a relationship, such as the relevant linear equation or spring constant, and then use that model to predict displacements it has not observed.

Simon
So traditional programming usually means that a programmer supplies the program, the computer receives data, and the program produces an output. In a machine-learning approach, we provide examples, data, and often labels describing the desired outputs. The learning algorithm then produces a model or program that can infer new information from later inputs.

Hope
That distinction is important because learning should go beyond memorizing facts. Memorization is declarative knowledge: storing statements of truth and hoping the next question repeats one of them. A stronger form of learning infers new information from old information, using patterns that may be implicit in the data rather than rules explicitly written by the programmer.

Simon
The general machine-learning loop has three parts. First, we supply training data, which consists of observations or examples. Second, an inference process learns something about the process that generated those observations. Third, the resulting model makes predictions about new examples that were not in the training data.

Hope
The spring example contains all three parts: training data made up of masses and displacements, an inference process that finds the underlying relationship, and a model that predicts a new displacement. A more common setting involves examples represented by features and, sometimes, labels. For instance, a football player might be represented by height and weight, with the label being the position the player plays.

Simon
That gives us the two broad categories of learning. In supervised learning, every training example has a known label, and the algorithm learns a rule for predicting labels on unseen examples. In unsupervised learning, the examples have no known labels, so the algorithm tries to discover natural groups or structures in the data.

Hope
Classification is the standard supervised-learning example. Suppose we have labeled Patriots players: some are receivers and some are linemen. If height and weight distinguish those labeled groups, we can learn a boundary in that feature space and use it to classify a new player.

Simon
Clustering is the corresponding unsupervised idea. If we only know that the data contain two groups, but do not know which player belongs to which group, we can seek clusters in which examples are close to one another and reasonably far from examples in the other clusters.

Hope
A standard clustering procedure begins by selecting two representative examples, or exemplars, ideally ones that are not too close together. Every other example is assigned to whichever exemplar it is closest to. Then we find the median example of each cluster—the example closest to the cluster’s center—use those as new exemplars, and repeat until the assignments stop changing or we have repeated the process enough times.

Simon
Using only player weight can produce a fairly natural division between the heavier linemen and lighter receivers. Height alone may separate them less cleanly. Combining height and weight can produce a more useful two-dimensional grouping, with a dividing line consisting of points equally distant from the centers of the two clusters.

Hope
That line can be used to label new players. A new point on one side is assigned to one group, and a point on the other side is assigned to the other. But the method also exposes uncertainty. Two new running backs might be close to the receiver group, while another could lie almost exactly on the boundary, making its classification unclear.

Simon
If we know the labels in advance, we can use them directly rather than relying only on naturally occurring clusters. In the football example, the labeled data suggest a simple boundary: players above roughly 280 pounds are more likely to be linemen, while those below that threshold are more likely to be receivers.

Hope
A classifier does not always have to be one straight line. It might use a plane in a higher-dimensional feature space, several line segments, or another more complicated surface. But complexity creates a danger: a boundary can fit the training examples extremely well while performing poorly on new examples. That is overfitting, so we may prefer a simpler boundary even if it misclassifies a few training examples.

Simon
That leads to a general design problem: every learning method needs appropriate training data and a way to evaluate success. We also need a representation for each example, a way to measure distance or similarity between examples, an objective that tells us what counts as a good model, and an optimization method for finding that model.

Hope
The representation is built from features. Height and weight were convenient features for football players, but perhaps speed, arm length, or some combination would be more informative for deciding a player’s position. Feature engineering means choosing which properties to measure and deciding how those properties should be represented.

Simon
Some features carry signal and others mostly add noise. Imagine trying to predict a student’s performance using grade point average and prior programming experience. Those might provide useful information, although neither is perfect. Birth month or eye color, by contrast, would not be expected to tell us much, and adding irrelevant features can create accidental correlations that encourage overfitting.

Hope
The reptile example makes feature selection more concrete. At first, a cobra is described as egg-laying, scaled, poisonous, cold-blooded, legless, and a reptile. A second similar example might suggest a rule requiring all those properties, but a boa constrictor shows that the rule is too strict because it is not poisonous and does not fit the egg-laying description used in the example.

Simon
So we refine the features. Scales, being cold-blooded, and having a particular leg pattern can describe the examples more successfully. A chicken provides a useful negative example: it may have scales, but it is not cold-blooded and has legs, so it should not be classified as a reptile. An alligator then forces another refinement because it is a reptile with legs.

Hope
Eventually, the examples include a dart frog, a python, and a salmon. The python and salmon create a conflict: using only scales, cold-bloodedness, and number of legs, there is no perfect rule that labels the python as a reptile and the salmon as not a reptile. A reasonable design choice is to use scales and cold-bloodedness, accepting that the salmon becomes a false positive.

Simon
A false positive occurs when the classifier predicts that an example belongs to the target class, but it does not. A false negative is the reverse: the classifier fails to identify an example that really belongs to the target class. Because real data may overlap, choosing a model often means deciding which kinds of errors are more acceptable.

Hope
After choosing features, we need a distance measure. We can represent a feature vector numerically—for example, true as 1, false as 0—and compare two vectors component by component. The choice of distance matters because clustering and classification both depend on what the algorithm considers close.

Simon
A general family is the Minkowski metric. For two vectors and a power p, take the absolute difference in each component, raise each difference to the p-th power, add the results, and take the p-th root of the sum. When p equals 1, we get Manhattan distance: the absolute component differences are added. When p equals 2, we get Euclidean distance, the familiar square-root-of-the-sum-of-squared-differences.

Hope
The two metrics can rank pairs differently. In a geometric example, Euclidean distance measures the direct diagonal distance, while Manhattan distance measures movement along horizontal and vertical paths, like traveling along streets and avenues. A pair that is closer under Euclidean distance need not be the pair that is closer under Manhattan distance.

Simon
Feature scales are another major issue. Suppose an animal vector contains several binary features and one integer feature recording the number of legs. Under Euclidean distance, the difference between zero legs and four legs can dominate several binary differences, even though the number-of-legs scale may not deserve that much influence.

Hope
There are at least two ways to address that problem. We might use Manhattan distance, which treats the component differences more directly, or we might recode the number-of-legs feature as a binary property: no legs versus some legs. With that change, the alligator can be closer to the snakes than to the dart frog, producing a more useful reptile grouping.

Simon
So feature engineering includes not only which features we choose, but also how we scale and encode them. Adding many features can increase noise or overfitting, and an inappropriate scale can make one dimension dominate the distance. The designer’s choices strongly influence what the learning algorithm discovers.

Hope
For unsupervised learning, we also have to decide how many clusters to seek. If there are one hundred examples, creating one hundred clusters gives perfect closeness within each cluster but is useless for generalization. We want a number and a structure that capture meaningful groups without constructing an unnecessarily complicated explanation.

Simon
That is why validation matters. In the football example, two clusters looked reasonable before the new running-back points were considered, but one new point landed near the boundary. Trying three clusters produced tighter groups—five players in one, four in another, and three in an intermediate group—while trying to create even more clusters could overfit awkwardly close points.

Hope
For supervised learning, we can evaluate candidate separating surfaces using labeled data. Consider simulated voters described by age and distance from Boston, with labels indicating whether they tend to vote Democratic or Republican. One line might correctly separate all the Democrats but misclassify several Republicans; another might capture most Republicans on one side while leaving a mixture on the other.

Simon
A confusion matrix organizes those results by predicted label and actual label. The diagonal entries are correct predictions: true positives and true negatives. The off-diagonal entries are false positives and false negatives. Accuracy is the number of correct predictions—true positives plus true negatives—divided by the total number of predictions.

Hope
Two different lines in the voting example both achieved about 0.7 accuracy on the relevant data, so accuracy alone did not identify a clear winner. A more complicated boundary reduced the training errors and reached about 0.833 training accuracy, but its accuracy on test data was only about 0.6. That difference is a warning sign for overfitting.

Simon
Another measure is positive predictive value, or PPV. It asks: among all the examples the classifier labeled positively, what fraction were truly positive? This can reveal differences that overall accuracy hides, especially when the costs of false positives and false negatives are not the same.

Hope
Sensitivity and specificity describe another trade-off. Sensitivity measures how many actual positive examples the system correctly identifies. Specificity measures how many actual negative examples it correctly rejects. If we label everything as positive, sensitivity can reach one, but specificity falls to zero; if we reject everything, specificity can reach one, but sensitivity falls to zero.

Simon
An ROC, or Receiver Operating Characteristic, curve helps examine that trade-off across different classifier choices. The broader lesson is that there is rarely one universally best classifier. We must consider the features, their scales, the distance measure, the model’s complexity, the validation results, and whether false positives or false negatives are more costly.

Hope
One more supervised method is k-nearest neighbors. Given a new example and labeled training data, we find its k closest labeled examples and let them vote. If most of the neighbors share a label, we assign that label; if the evidence is not strong enough, the example can remain unclassified.

Simon
So the core picture is now complete. Machine learning uses examples to infer a model that can make predictions about unseen data. Supervised methods learn from labels, unsupervised methods discover groups without labels, and both depend on thoughtful representations, meaningful distances, suitable model complexity, and careful evaluation.

Hope
And that is why simple examples such as springs, football players, animals, and voters are useful. They expose the same decisions that appear in larger systems: what information to use, how to measure similarity, how to avoid overfitting, how to validate generalization, and how to balance different kinds of errors.

Ask anything
We've read this whole study set, so questions about it get the best answers.