Introduction to Machine Learning


Introduction to Machine Learning

Corey
Welcome back to our introduction to artificial intelligence with Python. So far, we've solved problems by giving computers explicit instructions about how to search for solutions or satisfy constraints. Today, we're shifting to machine learning, where the computer learns patterns from data instead of being told every step of the task.

Michael
Exactly. Machine learning means giving an AI information in the form of data or patterns, then allowing it to figure out how that information relates to the task. The goal is for the computer to learn a function that can perform the task on its own, even on inputs it has not seen before.

Corey
One major form is supervised learning. In supervised learning, the computer receives input-output pairs. It uses those examples to estimate a function that maps an input, such as evidence or measurements, to an output, such as a category or numerical value.

Michael
The important word is supervised because a human has labeled the training examples. The computer is not merely given raw data; it is shown the correct output associated with each input and asked to learn the relationship between them.

Corey
The first supervised task we'll discuss is classification. Classification means assigning an input to one of a set of discrete categories. For example, a banknote might be classified as authentic or counterfeit, or a day might be classified as rainy or not rainy.

Michael
Consider weather data. Each historical day could have input values such as humidity and air pressure, along with a human-provided label saying whether it rained. The model studies those labeled examples and tries to predict the label for a new day from its humidity and pressure.

Corey
Mathematically, we can call the unknown real-world relationship f. We don't usually know exactly what f looks like, because it may be very complex. Instead, the computer learns a hypothesis function h that takes the same inputs and tries to produce the same outputs as f.

Michael
With two numerical inputs, we can visualize the data on a graph. Put humidity on one axis and pressure on the other, then plot rainy days in blue and non-rainy days in red. When a new, unlabeled point appears, the model has to decide which category it belongs to.

Corey
A natural approach is nearest neighbor classification. The algorithm finds the training point closest to the new input and assigns the new input that point's class. If the closest historical day was rainy, the prediction is rainy; if it was not rainy, the prediction is not rainy.

Michael
That method is intuitive, but a single closest point can sometimes be misleading. A new point might be closest to one red point while being surrounded by many blue points. In that situation, looking at several nearby examples may provide a better judgment.

Corey
That is the idea behind k-nearest-neighbor classification. We choose a value for k, such as three, five, or seven, find the k closest data points, and select the most common class among them. Each neighbor effectively casts one vote, so three rainy neighbors and two non-rainy neighbors produce a rainy prediction.

Michael
Different machine-learning algorithms have different strengths and weaknesses. No single algorithm is always best. The right choice depends on the data and on the function we are trying to estimate, so machine-learning work often involves testing several approaches.

Corey
One drawback of a naive nearest-neighbor method is speed. It may need to measure the distance from a new point to every stored point. Data structures, pruning, and removing less relevant points can help, but another strategy is to find a decision boundary that separates the categories.

Michael
With two inputs, a decision boundary can be a line. Linear approaches try to find a line that separates rainy days from non-rainy days. Real data may contain noise and outliers, so the categories are not always perfectly linearly separable; in that case, we look for a line that makes the fewest or smallest errors.

Corey
To describe that line mathematically, let x1 represent humidity and x2 represent pressure. The hypothesis combines those inputs with weights: w0 plus w1 times x1 plus w2 times x2. If the result is greater than or equal to zero, we can output one, meaning rainy; otherwise, we output zero, meaning not rainy.

Michael
The weights determine the boundary's slope, position, and overall shape. The inputs are the evidence for the particular data point, while the weights are parameters that the learning algorithm must discover. Random weights produce a hypothesis, but not necessarily an accurate one.

Corey
This calculation can also be written using vectors. The weight vector is w equals the sequence of w0, w1, and w2. The input vector is x equals one, x1, and x2, where the initial one lets w0 be included in the same calculation.

Michael
The dot product of w and x multiplies corresponding values and adds the results: w0 times one, plus w1 times x1, plus w2 times x2. The hypothesis checks whether that dot product reaches the threshold. With more input variables, the vectors simply become longer.

Corey
A common way to learn the weights is the perceptron learning rule. Start with some weights, possibly random ones, then examine labeled data points one at a time. If the prediction is correct, the weights do not need to change; if the prediction is wrong, update them so the model is more likely to classify similar data correctly later.

Michael
The update depends on the difference between the actual output y and the predicted output h of x. If those values are equal, their difference is zero, so the weights remain unchanged. If the actual value is larger than the prediction, the update tends to increase the weights; if the prediction is too large, the update tends to decrease them.

Corey
The parameter alpha is the learning rate. A larger alpha makes bigger updates, while a smaller alpha makes more gradual updates. Repeating the process across many data points, possibly more than once, can move the weights toward a function that predicts the labels more accurately.

Michael
This produces a hard threshold: the output is either zero or one. That is useful when we only need a category, but it gives no sense of confidence. A point far inside the rainy region and a point right next to the boundary may both receive exactly the same output.

Corey
Logistic regression addresses that limitation with a soft threshold, called a logistic function. Instead of jumping directly from zero to one, it can output any real value between zero and one. A value such as 0.7 can represent that rain is more likely than not, while still expressing less confidence than a value near one.

Michael
Another approach is the support vector machine, or SVM. If several lines separate the training categories perfectly, an SVM tries to choose the maximum-margin separator: the boundary that has the greatest distance from the closest points in the groups.

Corey
Those closest points are called support vectors. Choosing a boundary with a wider margin can help the model generalize to new data instead of depending too closely on the exact training points. In higher dimensions, the boundary is generally called a hyperplane rather than a line.

Michael
SVMs can also help when the data is not linearly separable. By operating in higher-dimensional spaces, they may find a boundary that is not a straight line in the original view, such as a circular boundary separating a central group from points surrounding it.

Corey
Classification is not the only supervised-learning task. Regression also learns a function mapping inputs to outputs, but the output is a continuous real number rather than a discrete category.

Michael
For example, a company could use past data about advertising spending and sales. Advertising dollars would be the input, sales would be the numerical output, and a regression model could fit a line that estimates expected sales for a particular advertising budget.

Corey
Once we have a hypothesis, we need a way to evaluate it. This can be viewed as an optimization problem: either maximize an objective or, more commonly here, minimize a cost. A loss function estimates how poorly the hypothesis performs.

Michael
For classification, one simple option is the zero-one loss function. If the prediction matches the actual label, the loss for that data point is zero. If the prediction is wrong, the loss is one. Adding the losses across the data points gives the total empirical loss.

Corey
For regression, we often care about how far the prediction is from the actual value. L1 loss uses the absolute difference between actual and predicted values, then sums those differences across the data. Predicting 2,900 in sales when the actual value is 2,800 is therefore treated as a smaller error than predicting 1,000.

Michael
L2 loss squares the difference between the actual and predicted values. Because larger errors are squared, L2 penalizes them more heavily. The choice between L1 and L2 depends on the problem and on how we want to treat large errors and outliers.

Corey
A major danger when minimizing loss is overfitting. Overfitting happens when a model fits the training data too closely and fails to generalize to new examples. A complicated boundary might classify every historical weather example correctly while making poor predictions about future days.

Michael
The same problem appears in regression. A smooth line may capture the overall relationship between advertising and sales, while a highly complicated curve that passes through every training point can have zero training loss but perform poorly on future data.

Corey
One way to reduce overfitting is regularization. Instead of defining cost as loss alone, we include a penalty for the complexity of the hypothesis. This favors simpler boundaries or functions that may generalize better, following an approach similar to Occam's razor.

Michael
The complexity penalty can be multiplied by a parameter called lambda. A larger lambda penalizes complexity more strongly, while a smaller lambda allows a more complex hypothesis. There is no universally correct value; it depends on the data and the problem, so experimentation may be necessary.

Corey
Another way to test generalization is holdout cross-validation. Split the data into a training set and a testing set. Train the model only on the training set, then evaluate it on the separate testing set that the model has not seen.

Michael
If the model generalizes well, it should perform well on the testing examples. If it overfit the training data, its testing performance will usually be worse. The testing set is important because evaluating only on training data can hide overfitting.

Corey
A single holdout split does mean that some data is not used for training. K-fold cross-validation addresses that by dividing the data into k groups. With ten groups, for example, train on nine groups and test on the remaining group, repeating the process until each group has served as the held-out test set.

Michael
That produces ten performance results, which can be averaged to estimate overall performance. The central principle is still the same: train on one portion and test on different data so we can assess whether the model generalizes.

Corey
In Python, scikit-learn provides implementations of many of these algorithms, including perceptrons, support vector classifiers, and nearest-neighbor classifiers. It lets programmers use practical machine-learning models without implementing every mathematical detail from scratch.

Michael
The banknote example makes this concrete. The CSV file contains rows for banknotes, four measured input values for each note, and a human-provided label. A label of zero represents an authentic note, while a label of one represents a counterfeit note.

Corey
The program separates each row into evidence and a label, shuffles the data, and divides it into training and testing sets. It then creates input vectors from the four measurements and output values from the labels, fits a model on the training data, and predicts labels for the testing data.

Michael
The predictions are compared with the actual testing labels to count correct and incorrect classifications and calculate accuracy. In the example, a perceptron classified 679 notes correctly and seven incorrectly, for close to 99 percent accuracy.

Corey
The same data can be tested with other models. The support vector classifier correctly classified 682 and incorrectly classified four, for about 99.4 percent accuracy. A one-neighbor classifier correctly classified 685 and missed one, while the three-neighbor version reached 100 percent on that particular split.

Michael
Those results should not be interpreted as a universal ranking. The data is randomly reorganized, so different runs use slightly different training and testing sets, and another dataset could favor a different algorithm. Scikit-learn's train_test_split function can automate the splitting, making these experiments much shorter to write.

Corey
Now let's move to another major kind of learning: reinforcement learning. Instead of receiving a labeled collection of input-output pairs, an agent learns from experience by interacting with an environment.

Michael
The agent may be a physical robot or a virtual program. It observes a state, chooses an action, and then receives a new state and a numerical reward. Positive values represent rewards, while negative values represent punishments, and the agent uses those consequences to improve future decisions.

Corey
A walking robot illustrates the idea. Rather than explicitly programming every movement, we could reward steps that move it forward and punish it when it falls. Through repeated experience, the robot can learn which actions tend to help and which tend to hurt.

Michael
A useful formal model is a Markov decision process. A Markov chain transitions between states according to probabilities, without an agent controlling the process. A Markov decision process adds an agent that can choose among actions available in the current state.

Corey
Each state-action choice has a transition model describing the probability of ending up in each possible next state. The world may be deterministic, where a state and action always lead to the same result, or uncertain, where several next states have different probabilities.

Michael
The process also includes a reward function. It specifies the reward for starting in a state, taking an action, and arriving at a next state. By accumulating rewards over actions, we can describe how successful an agent's interaction with the environment has been.

Corey
One reinforcement-learning method is Q-learning. It learns a function Q of state and action, written Q of s comma a, that estimates the value of taking action a in state s. Initially, the agent can set every Q value to zero because it has no experience.

Michael
Whenever the agent takes an action and observes a reward, it updates the relevant Q value. The new estimate includes the immediate reward plus the best expected future reward available from the next state.

Corey
The update combines the old estimate with the new estimate. The learning rate alpha controls how much new information matters compared with old information. If alpha is zero, the new information is ignored; if alpha is one, the new estimate completely replaces the old one; values between zero and one balance the two.

Michael
Future rewards can also be discounted if the programmer wants immediate rewards to count more than rewards received later. Once the Q values are reasonably accurate, a greedy policy chooses, in each state, the action with the highest estimated Q value.

Corey
But always choosing the action currently believed to be best creates a problem. The agent may repeatedly exploit a known route without discovering a faster or more rewarding route. That is the tension between exploitation, which uses existing knowledge, and exploration, which tries actions whose results are less certain.

Michael
The epsilon-greedy strategy balances them. With probability one minus epsilon, choose the currently estimated best action. With probability epsilon, choose a random action, allowing the agent to explore possibilities it might otherwise ignore.

Corey
The value of epsilon can be reduced over time. Early in learning, more random exploration can help the agent discover the environment. Later, once it has more experience, it can rely more often on the actions it believes will work best.

Michael
Games are a common reinforcement-learning application. The agent can play repeatedly and receive a reward when it wins, such as one, and a punishment when it loses, such as negative one. It can learn from playing against people or by playing against itself.

Corey
Nim is a simple example. There are several piles of objects, and players take turns removing at least one object from exactly one pile. A player may remove as many objects as desired from that pile, but the player who removes the last object loses.

Michael
Nim is convenient for reinforcement learning because a state can be represented by the number of objects in each pile, and actions specify how many objects to remove from which pile. An AI can play many practice games against itself, using wins and losses to learn the values of different state-action choices.

Corey
With no training, the AI makes essentially random decisions, so a human can often win easily. After training on thousands of games, however, the AI can learn patterns about which moves are good or bad and make much stronger decisions.

Michael
Larger games such as chess have vastly more possible states and actions, making it impractical to learn an exact Q value for every state-action pair. Function approximation helps by estimating values from features of states, allowing knowledge from one situation to generalize to similar situations.

Corey
The third major category is unsupervised learning. Here, the data has no labels or additional feedback. The system must discover useful patterns or groupings on its own rather than learning from known correct outputs.

Michael
A key unsupervised task is clustering: organizing objects into groups whose members are similar to one another. Applications include grouping similar genes, dividing image pixels into regions, and identifying consumer groups for market research.

Corey
One clustering method is k-means clustering. We choose a number k for the desired number of clusters, place k centers initially, and assign every data point to the center it is closest to.

Michael
Then we recenter each cluster by moving its center to the average location of the points assigned to it. Because the centers moved, some points may now be closer to a different center, so we assign them again.

Corey
The assignment and recentering steps repeat. Eventually, the assignments stop changing, producing an equilibrium in which each point belongs to the cluster whose center is closest under the current arrangement.

Michael
Unlike supervised learning, k-means does not need labels telling it what the groups are. It discovers groups from the structure of the data, although the programmer must choose the value of k and can experiment with different choices.

Corey
So the big picture is that machine learning lets computers learn patterns from data rather than relying only on explicit instructions. Supervised learning uses labeled input-output pairs, reinforcement learning uses experience and rewards, and unsupervised learning finds structure in unlabeled data.

Michael
Within those categories, we saw several foundational ideas: nearest neighbors, perceptrons and linear decision boundaries, logistic regression's soft threshold, support vector machines, regression, loss functions, regularization, cross-validation, Q-learning, exploration versus exploitation, and k-means clustering.

Corey
And the recurring lesson is that the best method depends on the problem and the data. We evaluate hypotheses with appropriate loss or accuracy measures, guard against overfitting by emphasizing generalization, and use tools such as scikit-learn to apply these methods in Python.

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