<jupyter_start><jupyter_text>Finding linesIn [The Mean and Slopes](mean_and_slopes), we were looking for the best slopeto predict one vector of values from another vector of values.Specifically, we wanted our slope to predict the Packed Cell Volume (PCV)values from the Hemoglobin (HGB) values.By analogy with [The Mean as Predictor](mean_meaning), we decided to choose ourline to minimize the average prediction errors, and the sum of squaredprediction errors.We found a solution, by trying many slopes, and choosing the slope giving usethe smallest error.For our question, we were happy to assume that the line passed through 0,0 --- meaning, that when the Hemoglobin is 0, the Packed Cell Volume value is 0.Put another way, we assumed that our line had an *intercept* value of 0.  Theintercept is the y value at which the line crosses the y axis, or, put anotherway, the y value when the x value is 0.What if we are in a situation where we want to find a line that had a (notzero) intercept, as well as a slope?*Note: please see [this page](Lines_Slopes_and_Intercepts_-_Refresher) if you would likea refresher on intercepts, slopes and linear graphs*<jupyter_code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# Make plots look a little bit more fancy
plt.style.use('fivethirtyeight')
# Print to 4 decimal places, show tiny values as 0
np.set_printoptions(precision=4, suppress=True)<jupyter_output><empty_output><jupyter_text>We return to the [students ratings dataset](../data/rate_my_professors) dataset.This is a dataset, in Excel form, where each row is the average of students'ratings from  across a single subject.  Thus, the firstrow refers to the average of all professors teaching English, the second rowrefers to all professors teaching Mathematics, and so on.Download the data file via this link {download}`rate_my_course.csv `.Next we load the data.<jupyter_code># Read the data file
ratings = pd.read_csv('rate_my_course.csv')
ratings.head()<jupyter_output><empty_output><jupyter_text>We are interested in the relationship of the "Overall Quality" measure to the"Easiness" measure.<jupyter_code># Convert Easiness and Overall Quality measures to arrays.
easiness = np.array(ratings['Easiness'])
quality = np.array(ratings['Overall Quality'])<jupyter_output><empty_output><jupyter_text>Do students rate easier courses as being of better quality?<jupyter_code>plt.plot(easiness, quality, 'o')
plt.xlabel('Easiness')
plt.ylabel('Overall Quality')<jupyter_output><empty_output><jupyter_text>There might be a straight-line relationship here, but it doesn't look as if itwould go through 0, 0:<jupyter_code># The same plot as above, but showing the x, y origin at 0, 0
plt.plot(easiness, quality, 'o')
plt.xlabel('Easiness')
plt.ylabel('Overall Quality')
# Make sure 0, 0 is on the plot.
plt.axis([0, 3.9, 0, 4.2])<jupyter_output><empty_output><jupyter_text>In [The Mean and Slopes](mean_and_slopes), we assumed that the intercept was zero, so we only had to try different slopes to get our best line. Here we have a different problem, because we want to find a line that has anintercept that is not zero, so we need to find the *best slope* and the *bestintercept* at the same time.  How do we search for a slope as well as anintercept? But wait - why do we have to search for the slope and the intercept *at the same time*?  Can't we just find the best slope, and then the best intercept?In fact we can't do that, because the best slope will change for every intercept.To see why that is, we need to try a few different lines.   To do that, we need to remind ourselves about defining lines, and then testing them. Remember, we can describe a line with an *intercept* and a *slope*.  Call the*intercept* $c$ and a *slope* $s$.  A line predicts the $y$ values from the$x$ values, using the slope $s$ and the intercept $c$:$$y = c + x * s$$ Let's start with a guess for the line, just from eyeballing the plot. We guessthat:* The intercept is around 2.25* The slope is around 0.47The *predicted* $y$ values from this line are (from the formula above):<jupyter_code>predicted = 2.25 + easiness * 0.47<jupyter_output><empty_output><jupyter_text>where `easiness` contains our actual $x$ values.The prediction error at each point come from the actual $y$ values minus thepredicted $y$ values.<jupyter_code>error = quality - predicted<jupyter_output><empty_output><jupyter_text>where `quality` contains our actual $y$ values.We can look at the *predictions* for this line (in red), and the actual values (in blue) and then the errors (the lengths of the dotted lines joining the red predictions and the corresponding blue actual values).<jupyter_code># Don't worry about this code, it's just to plot the line, and the errors.
x_values = easiness  # The thing we're predicting from, on the x axis
y_values = quality  # The thing we're predicting, on the y axis.
plt.plot(x_values, y_values, 'o')
plt.plot(x_values, predicted, 'o', color='red')
# Draw a line between predicted and actual
for i in np.arange(len(x_values)):
    x = x_values[i]
    y_0 = predicted[i]
    y_1 = y_values[i]
    plt.plot([x, x], [y_0, y_1], ':', color='black', linewidth=1)<jupyter_output><empty_output><jupyter_text>The sum of squared errors is:<jupyter_code># Sum of squared error given c and s
sse_c_s = np.sum(error ** 2)
sse_c_s<jupyter_output><empty_output><jupyter_text>Actually, those bits of code are so useful, let's make them into a function:<jupyter_code>def plot_with_errors(x_values, y_values, c, s):
    """ Plot a line through data with errors

    Parameters
    ----------
    x_values : array
        Values we are predicting from, for the x-axis of the plot.
    y_values : array
        Values we are predicting, for the y-axis of the plot.
    c : number
        Intercept for predicting line.
    s : number
        Slope for predicting line.

    Returns
    -------
    s_o_s : number
        The sum of squares of the errors, for the given `x_values`, `y_values` and line.
    """
    # Predict the y values from the line.
    predicted = c + s * x_values
    # Errors are the real values minus the predicted values.
    errors = y_values - predicted
    # Plot real values in blue, predicted values in red.
    plt.plot(x_values, y_values, 'o', color='blue')
    plt.plot(x_values, predicted, 'o', color='red')
    # Draw a line between predicted and actual
    for i in np.arange(len(x_values)):
        x = x_values[i]
        y_0 = predicted[i]
        y_1 = y_values[i]
        plt.plot([x, x], [y_0, y_1], ':', color='black', linewidth=1)
    return np.sum(errors ** 2)<jupyter_output><empty_output><jupyter_text>Notice the string at the top of the function, giving details about what the function does, its arguments, and the values it returns.  This is called the *docstring*.  It can remind you and other people what the function does, and how to use it.  Try making a new cell and type `plot_with_errors?`.  You'll see this string is the help that Python will fetch for this function.Now the same thing with the function:<jupyter_code>plot_with_errors(easiness, quality, 2.25, 0.47)<jupyter_output><empty_output><jupyter_text>If we try a different intercept, we'll get a different line, and a differenterror.  Let's try an intercept of 2.1:<jupyter_code>plot_with_errors(easiness, quality, 2.1, 0.47)<jupyter_output><empty_output><jupyter_text>Or, we could go back to the same intercept, but try a different slope, and we'd get a different error.  Let's try a slope of 0.5:<jupyter_code>plot_with_errors(easiness, quality, 2.25, 0.5)<jupyter_output><empty_output><jupyter_text>Now we use the long slow method to find the best slope for our initialintercept of 2.25.  You may recognize the following from the [mean andslopes](mean_and_slopes) notebook.First we make a function, a bit like the function above, that gives us theerror for any given intercept (`c`) and slope (`s`) like this:<jupyter_code>def sos_error_c_s(c, s):
    predicted = c + easiness * s
    error = quality - predicted
    return np.sum(error ** 2)<jupyter_output><empty_output><jupyter_text>We have already calculated the error for the original guess at slope and intercept, but let's do it again for practice:<jupyter_code># Sum of squared error for our initial guessed line.
predicted = 2.25 + easiness * 0.47
error = quality - predicted
np.sum(error ** 2)<jupyter_output><empty_output><jupyter_text>Check that our function gives the same value for the same intercept and slope:<jupyter_code>sos_error_c_s(2.25, 0.47)<jupyter_output><empty_output><jupyter_text>OK, now we use this function to try lots of different slopes, for thisintercept, and see which slope gives us the lowest error.  See the means,slopes notebook for the first time we did this.<jupyter_code># Some slopes to try.
some_slopes = np.arange(-2, 2, 0.001)
n_slopes = len(some_slopes)
print('Number of slopes to try:', n_slopes)
# The first 10 slopes to try:
some_slopes[:10]
# Try all these slopes for an intercept of 2.25
# For each slope, calculate and record sum of squared error
sos_errors = np.zeros(n_slopes)
for i in np.arange(n_slopes):
    slope = some_slopes[i]
    sos_errors[i] = sos_error_c_s(2.25, slope)<jupyter_output><empty_output><jupyter_text>Now plot the errors we got for each slope, and find the slope giving the smallest error:<jupyter_code>plt.plot(some_slopes, sos_errors)
plt.xlabel('Candidate slopes')
plt.ylabel('Sum of squared error')<jupyter_output><empty_output><jupyter_text>Using the tricks from [where and argmin](where_and_argmin), we find the index(position) of the minimum value, and then find the corresponding slope.<jupyter_code>i_of_best_slope = np.argmin(sos_errors)
best_slope_for_2p25 = some_slopes[i_of_best_slope]
print('Best slope for intercept of', 2.25, 'is', best_slope_for_2p25)<jupyter_output><empty_output><jupyter_text>That code also looks useful, so let's make some of that code into a function wecan re-use:<jupyter_code>def best_slope_for_intercept(intercept, some_slopes):
    """ Calculate best slope, lowest error for a given intercept

    Parameters
    ----------
    intercept : number
        Intercept.
    some_slopes : array
        Array of candidate slope values to try.

    Returns
    -------
    best_slope : float
        Slope from `some_slopes` that results in lowest error.
    lowest_error : float
        Lowest error score across all slopes in `some_slopes`;
        therefore, error score for `best_slope`.
    """
    n_slopes = len(some_slopes)
    # Try all these slopes, calculate and record sum of squared error
    sos_errors = np.zeros(n_slopes)
    for i in np.arange(n_slopes):
        slope = some_slopes[i]
        sos_errors[i] = sos_error_c_s(intercept, slope)
    i_of_best_slope = np.argmin(sos_errors)
    # Return the slope and associated error as a length 2 array.
    return np.array(
        [some_slopes[i_of_best_slope], sos_errors[i_of_best_slope]]
    )<jupyter_output><empty_output><jupyter_text>Now use the function to find the best slope:<jupyter_code>best_slope_for_intercept(2.25, some_slopes)<jupyter_output><empty_output><jupyter_text>OK --- that's the best slope and error for an intercept of 2.25.  How about ourother suggestion, of an intercept of 2.1?  Let's try that:<jupyter_code>best_slope_for_intercept(2.1, some_slopes)<jupyter_output><empty_output><jupyter_text>Oh dear - the best slope has changed.  And, in general, for any intercept, youmay able to see that the best slope will be different, as the slope tries toadjust for the stuff that the intercept does not explain.This means we can't just find the intercept, and find the best slope for thatintercept, at least not in our case - we have to find the best *pair* ofintercept and slope.  This is the pair, of all possible pairs, that gives thelowest error. Our task then, is to find the *pair of values* --- `c` and `s`  --- such thatwe get the smallest possible value for the sum of squared errors above. One way of doing this, is to try *every possible* plausible pair of interceptand slope, calculate the error for this pair, and then find the *pair* thatgave the lowest error.We are now searching over many *combinations* of slopes and intercepts. For example, say we were interested in trying the intercepts 2, 2.1, 2.2.  Thenwe'd run the routine above for each intercept, to find the best slope for each:<jupyter_code>print('Best slope, error for 2.0 is ',
      best_slope_for_intercept(2.0, some_slopes))
print('Best slope, error for 2.1 is ',
      best_slope_for_intercept(2.1, some_slopes))
print('Best slope, error for 2.2 is ',
      best_slope_for_intercept(2.2, some_slopes))<jupyter_output><empty_output><jupyter_text>From this we conclude that, of the intercepts we have tried, 2.1 is the best,because we could get the lowest error score with that intercept.  If this wasall we had, we would chose an intercept of 2.1, and its matching best slope of0.513. To find out if this is really the best we can do, we can try many intercepts.For each intercept, we find the best slope, with the lowest error.  Then wechoose the intercept for which we can get the lowest error, and find the bestslope for that intercept.<jupyter_code># Some intercepts to try
some_intercepts = np.arange(1, 3.2, 0.01)
n_intercepts = len(some_intercepts)
print('Number of intercepts to try:', n_intercepts)
# First 10 intercepts to try
print('First 10 intercepts', some_intercepts[:10])<jupyter_output><empty_output><jupyter_text>For each of the 220 possible intercepts, we try all 4000 possible slopes, tofind the slope giving the lowest error *for that intercept*.  We store the bestslope, and the best error, for each intercept, so we can chose the bestintercept, after we have finished.<jupyter_code># An array to collect the best slope found for each intercept.
best_slopes = np.zeros(n_intercepts)
# An array to collect the lowest error found for each intercept.
# This is the error associated with the matching slope above.
lowest_errors = np.zeros(n_intercepts)
# Cycle through each intercept, finding the best slope, and lowest error.
for i in np.arange(n_intercepts):
    # Intercept to try
    intercept = some_intercepts[i]
    # Find best slope, and matching error.
    slope_error = best_slope_for_intercept(intercept, some_slopes)
    # Store the slope and error in their arrays.
    best_slopes[i] = slope_error[0]  # The best slope
    lowest_errors[i] = slope_error[1]  # The matching error
print('First 10 intercepts:\n', some_intercepts[:10])
print('Best slopes for first 10 intercepts:\n', best_slopes[:10])
print('Lowest errors for first 10 intercepts:\n', lowest_errors[:10])
# Plot the lowest error for each intercept
plt.plot(some_intercepts, lowest_errors)
plt.xlabel('Intercepts')
plt.ylabel('Lowest error for intercept')
plt.title('Lowest error for each intercept')
# The lowest error we found for any intercept:
min(lowest_errors)<jupyter_output><empty_output><jupyter_text>Notice that this error is lower than the error we found for our guessed `c` and`s`:<jupyter_code>sos_error_c_s(2.25, 0.47)<jupyter_output><empty_output><jupyter_text>Again, we use [argmin](where_and_argmin) to find the index (position) of theminimum value:<jupyter_code># The index (position) of this lowest error
i_for_lowest = np.argmin(lowest_errors)
i_for_lowest
# The intercept corresponding to the lowest error
best_intercept = some_intercepts[i_for_lowest]
best_intercept
# The slope giving the lowest error, for this intercept
best_slope = best_slopes[i_for_lowest]
best_slope<jupyter_output><empty_output><jupyter_text>Plot the data, predictions and errors for the line that minimizes the sum ofsquared error:<jupyter_code>plot_with_errors(easiness, quality, best_intercept, best_slope)<jupyter_output><empty_output><jupyter_text>Now you know about [optimization](optimization), you will not be surprised todiscover that Scipy `minimize` can also do the search for the intercept andslope pair for us.  We send `minimize` the function we are trying to minimize,and a starting guess for the intercept and slope. `minimize` is a little fussy about the functions it will use.  It insists that all the parameters need to be passed in as a single argument.   In our case, we need to pass both parameters (the intercept and slope) as one value, containing two elements, like this:<jupyter_code>def sos_error_for_minimize(c_s):
    # c_s has two elements, the intercept c and the slope s.
    c = c_s[0]
    s = c_s[1]
    predicted = c + easiness * s
    error = quality - predicted
    return np.sum(error ** 2)<jupyter_output><empty_output><jupyter_text>This is the form of the function that minimize can use.  See [usingminimize](using_minimize) for more detail.We first confirm this gives us the same answer we got before from our function with two arguments:<jupyter_code># The original function
sos_error_c_s(2.25, 0.47)
# The function in the form that minimize wants
# The two parameters go into a list, that we can pass as a single argument.
sos_error_for_minimize([2.25, 0.47])<jupyter_output><empty_output><jupyter_text>As usual with `minimize` we need to give a starting guess for the intercept andslope.  We will start with our initial guess of `[2.25, 0.47]`, but anyreasonable guess will do.<jupyter_code>from scipy.optimize import minimize
minimize(sos_error_for_minimize, [2.25, 0.47])<jupyter_output><empty_output><jupyter_text>Notice that `minimize` doesn't get exactly the same result as we found with thelong slow way above.  This is because the long slow way only tested interceptsthat were step-sizes of 0.01 apart (and slopes that were 0.001 apart).`minimize` can use much smaller step-sizes, and so finds a more accurateanswer.We won't spend any time justifying this, but this is also the answer we getfrom traditional fitting of the least-squares line, as implemented, forexample, in the Scipy `linregress` function:<jupyter_code>from scipy.stats import linregress
linregress(easiness, quality)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08092068774265114, 'fraction_numerical': 0.011980033277870216, 'mean_word_length': 4.839054404145077, 'pattern_counts': {'":': 0, '<': 129, '<?xml version=': 0, '>': 129, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '32', 'dir': 'jupyter-structured-clean-dedup', 'id': '79636', 'license': 'CC-BY-4.0', 'n_tokens_mistral': 5857, 'n_tokens_neox': 5520, 'n_words': 2254, 'path': 'mean-slopes/finding_lines.ipynb', 'repo_name': 'uob-ds/cfd2021', 'size': '18030'}