<jupyter_start><jupyter_text>Descending into MLAuthor: <NAME>   SourceThis content is based on the [Descending into ML](https://developers.google.com/machine-learning/crash-course/descending-into-ml/) section of Google's *Machine Learning Crash Course*. Learning objectives* A model is a way to predict the label for a given set of features.* Loss is a way of measuring how far the predicted label is from the actual label. Linear regression for fun and profit[Linear regression](https://en.wikipedia.org/wiki/Linear_regression) is a method for finding the straight line or hyperplane that best fits a set of points. > If you remember this from previous mathematical training -- great! If not, just think of it as drawing a *line of best fit* on your data. And if you don't know what that is, don't worry, I'll show you! Working with the Iris flower datasetLet's start by loading the [Iris flower data set](https://en.wikipedia.org/wiki/Iris_flower_data_set) introduced earlier.<jupyter_code>import pandas as pd
import numpy as np

iris_dataset = pd.read_csv('../nb-datasets/iris_dataset.csv')
iris_dataset
iris_dataset.head()
iris_dataset.describe()
iris_dataset.species.value_counts()<jupyter_output><empty_output><jupyter_text>This refers to three species of plants:* [*Iris versicolor*](https://en.wikipedia.org/wiki/Iris_versicolor) (purple iris or poison flag),* [*Iris virginica*](https://en.wikipedia.org/wiki/Iris_virginica) (Virginia iris), and* [*Iris setosa*](https://en.wikipedia.org/wiki/Iris_setosa) (bristle-pointed iris).  What's a "Sepal"?![An image illustrating petals and sepals side by side](../nb-images/Petal-sepal.jpg)![*Alcea rosea*, a plant with distinctive sepals and petals](../nb-images/Alcea_rosea3_ies.jpg)A sepal is the green leaf-like structure found underneath the petal in many flowers. [Sepals](https://en.wikipedia.org/wiki/Sepal) provides protection for the flower when budding, and support for it once it is blooming.Given that that is the case, we might expect plants with larger petals to also have larger sepals for additional support.  Can we predict the length of the petal of a plant from the length of its sepal?<jupyter_code>import matplotlib.pyplot as plt

iris_dataset.plot("sepal_length", "petal_length", kind="scatter")
plt.show()
iris1 = iris_dataset.plot(
    "sepal_length",
    "petal_length",
    kind="scatter",
    title="Petal and sepal length in three species of Iris"
)
iris1.set_xlabel("Sepal length (cm)")
iris1.set_ylabel("Petal length (cm)")
plt.show()<jupyter_output><empty_output><jupyter_text>Looks like the answer is... yes! If we draw a line across the plot, we can *predict* what the petal length might be for a plant given a particular sepal length.**That's all a model is!** -- something that can extrapolate from known data to predict what the value might be for a given input value.  Linear regression can define that model preciselyDrawing a line by hand is fine, but we would like to determine exactly how the petal length varies as the sepal length varies. Luckily, `matplotlib` can run a linear regression for us easily.<jupyter_code>iris_dataset.sepal_length.head()
iris_dataset.petal_length.head()<jupyter_output><empty_output><jupyter_text>Scikit-learn's LinearRegression module needs the data as a two-dimensional array:* It expects each row to contain multiple features.* It expects as many rows as there are data points.<jupyter_code>iris_dataset.sepal_length.values.reshape(-1, 1)
from sklearn.linear_model import LinearRegression

X = iris_dataset.sepal_length.values.reshape(-1, 1)
Y = iris_dataset.petal_length

model = LinearRegression()
model.fit(X, Y)
slopes = model.coef_
intercept = model.intercept_

print(slopes, intercept)<jupyter_output>[1.85750967] -7.0953814782793145<jupyter_text>In other words, based on the available data, we can construct a model that predicts a petal length given a particular sepal length.$$petal\_length = 1.8575 * sepal\_length - 7.095$$  The Equation of a LineYou may be familiar with this as the [equation of a line](https://en.wikipedia.org/wiki/Linear_equationOne_variable):$$ y = mx + c $$See how easy it is to predict a petal value given a sepal value: you just plug it into the equation! For example:<jupyter_code># What is the predicted petal length when the sepal length is 5cm?
sepal_length = 5
petal_length = 1.8575 * sepal_length - 7.095
print(petal_length)
# We could be more precise by plugging in the slope and intercept values directly.
petal_length = slopes[0] * sepal_length + intercept
print(petal_length)<jupyter_output>2.192166848827913<jupyter_text>Machine learning? For real?Yes! By convention, we write this equation like this when thinking about it in machine-learning terms:$$ y' = b + w_1x_1 $$Where:* $y'$ is the *predicted label* (the desired output), which in our example is the petal length in centimeters.* $b$ is the *bias* (the y-intercept, sometimes referred to as $w_0$), which in our example is 7.095 cm.* $w_1$ is the *weight* of feature 1, which is the same concept as the "slope" in the traditional equation of the line. In our example, this is 1.8575.* $x_1$ is a *feature* (a known input), which in our example is the sepal length.Writing it in this way makes it easy to extend our model when we are considering multiple features, such as sepal length and sepal width and many more. In that case, our equation would look like:$$ y' = b + w_1x_1 + w_2x_2 + w_3x_3 + \ldots + w_nx_n $$                                                                                                                 What does this model actually look like?We can draw this model onto our plot from earlier as a *line of best fit*.<jupyter_code>iris1 = iris_dataset.plot("sepal_length", "petal_length", kind="scatter", title="Petal and sepal length in three species of Iris", color="red")
iris1.set_xlabel("Sepal length (cm)")
iris1.set_ylabel("Petal length (cm)")

iris1.plot(iris_dataset.sepal_length, iris_dataset.sepal_length * slopes[0] + intercept, 'black')

plt.show()<jupyter_output><empty_output><jupyter_text>Err...You might have noticed that this is *not* a very good model:* There's a lot of points at the bottom of the figure that don't follow the predicted relationship.* Petal sizes above 3cm seem to be increasing less quickly as sepal size increases than the predicted relationship.Let's calculate the predicted petal length for each flower -- what does our model predict as compared to the actual petal length we see?<jupyter_code>data = pd.DataFrame({
    'sepal_length': iris_dataset.sepal_length,
    'petal_length': iris_dataset.petal_length
})
data['predicted_petal_length'] = data.sepal_length * slopes[0] + intercept
data.head()<jupyter_output><empty_output><jupyter_text>If we plot the predicted petal length against the actual petal length, what would we expect to see?<jupyter_code>predicted1 = data.plot('petal_length', 'predicted_petal_length', kind='scatter', color='red')
predicted1.plot(data.petal_length, data.petal_length, 'black')
plt.show()<jupyter_output><empty_output><jupyter_text>LossLoss is a number indicating how bad the model's prediction was on one particular data point. If the model's prediction is perfect, the loss is zero; otherwise, the loss is greater. **The goal of training a model is to find a set of *weights* and *biases* that have low loss, on average, across all examples.**In this example, we have **150 data points** that provide a feature (the sepal length) as well as the label (the petal length). We can use these to determine how much total loss our model has over this dataset by calculating predicted labels and comparing them to the actual labels.There are many different measures of loss. One common measure of loss that is particularly useful in linear regressions is *squared loss* (or $L_2$ loss). This is defined as *the square of the difference between the label and the prediction*. In other words, it is equal to:$$ = (predicted\ label - actual\ label)^2 $$$$ = (observation - prediction(x))^2 $$$$ = (y - y')^2 $$We can use this equation to find the loss for a single data point. What does this look like in Python?<jupyter_code>data['squared_error'] = (data.petal_length - data.predicted_petal_length)**2
data.head()<jupyter_output><empty_output><jupyter_text>But how can we measure our total loss across all our 150 data points? Mean Square Error (MSE)The Mean Square Error (MSE) can be calculated as the arithmetic mean of all squared losses in a particular dataset $D$. We can calculate this as the total squared loss divided by the number of data points, i.e.:$$ MSE = \frac{1}{N} \sum_{(x, y)\ \in\ D}{(y - y')^2} $$What does this look like in Python?<jupyter_code>data.squared_error.mean()<jupyter_output><empty_output><jupyter_text>Tada!We now have:* A model that allows us to *predict* (or *infer*) the petal length from the sepal length within this dataset.* A measure for determining how much the prediction varied from the actual *label*, i.e. its *loss*.* A measure for determining how well the model performed on a particular dataset.  ExercisesHere are a few exercises to test your understanding of this material.  Exercise 1In the [Iris flower dataset](https://en.wikipedia.org/wiki/Iris_flower_data_set), we looked at whether we could predict the petal length based on sepal length.For this exercise, try using the sepal width to predict petal width, find the equation of the line of best fit, and plot that line on the same graph.<jupyter_code>import pandas
import numpy
import matplotlib.pyplot as plt

# Import Iris dataset.
iris_dataset = # How can we load our dataset?

# Plot sepal widths against petal widths.
iris_dataset.plot(
  # How do we plot this dataset?
)
plt.show()
# Hmm, this is NOT looking good. Oh well, let's see how awful it is!
# Construct our model.
slope, intercept = # How do we calculate the slope (weight) and intercept (bias).
print(slope, intercept)
iris1 = iris_dataset.plot(
  # How do you plot a pretty graph?
)
iris1.set_xlabel("#TODO")
iris1.set_ylabel("#TODO")
iris1.plot(
  # How can you plot the line of best fit?
)
plt.show()<jupyter_output><empty_output><jupyter_text>Exercise 2For the model that predicts petal length from sepal length in Exercise 1, calculate the Mean Square Error (MSE).<jupyter_code># Calculate predicted petal widths.
iris_dataset['predicted_petal_width'] = # How?
iris_dataset['squared_error'] = # How??
print("The mean squared error is: ",
  # How???
)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08915800514923239, 'fraction_numerical': 0.011538094784018309, 'mean_word_length': 4.925423728813559, 'pattern_counts': {'":': 0, '<': 48, '<?xml version=': 0, '>': 49, 'https://': 9, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '486087', 'license': 'MIT', 'n_tokens_mistral': 3220, 'n_tokens_neox': 3071, 'n_words': 1296, 'path': 'assets/nb-lessons/03_Descending_into_ML.ipynb', 'repo_name': 'USDA-ARS-GBRU/ml-training-site', 'size': '10494'}