In the print dialog, choose "Save as PDF" as the destination.
Machine Learning, Week 3
Predict a house price with a straight line: fit it by hand with least squares, then model 5000 real houses in scikit-learn.
info, describe, a histogram and a correlation heatmapLinearRegression, read its coefficients, and predict a house by handWeek 3 of the plan
| Part | What we do | Time |
|---|---|---|
| 1 | The idea, least squares, a worked example by hand | 35 min |
| 2 | Notebook: explore and prepare the housing data | 20 min |
| 3 | Notebook: fit the model, read the coefficients | 20 min |
| 4 | Evaluate on the test set, your project | 15 min |
| 5 | Practice with answers, then takeaways | 30 min |
Part 1
A straight line through the data
y and one or more explanatory variables X.x: the input, for example the area incomeŷ ("y hat"): the predicted value, for example the priceb₁: the slope, the change in ŷ when x grows by 1b₀: the intercept, the value of ŷ at x = 0y is the true value, ŷ the predictionSSE: the sum of squared errors over all n pointsBy hand
Rows of USA_Housing.csv. x: income in $10,000, y: price in $100,000, rounded
| House | Income | Price | (x, y) |
|---|---|---|---|
| H1 | $50,016 | $497,368 | (5, 5) |
| H2 | $59,769 | $897,291 | (6, 9) |
| H3 | $69,529 | $995,137 | (7, 10) |
| H4 | $79,628 | $1,196,064 | (8, 12) |
| H5 | $89,548 | $1,403,803 | (9, 14) |
| House | (x − x̄, y − ȳ) | Product | (x − x̄)² |
|---|---|---|---|
| H1 | (-2, -5) | 10 | 4 |
| H2 | (-1, -1) | 1 | 1 |
| H3 | (0, 0) | 0 | 0 |
| H4 | (1, 2) | 2 | 1 |
| H5 | (2, 4) | 8 | 4 |
| House | ŷ | e = y − ŷ | e² |
|---|---|---|---|
| H1 | 5.8 | -0.8 | 0.64 |
| H2 | 7.9 | 1.1 | 1.21 |
| H3 | 10.0 | 0.0 | 0.00 |
| H4 | 12.1 | -0.1 | 0.01 |
| H5 | 14.2 | -0.2 | 0.04 |
| Line | SSE |
|---|---|
| ŷ = −3 + 2x | 7.0 |
| ŷ = −4 + 2x | 2.0 |
| ŷ = −4.7 + 2.1x | 1.9 |

yy, and big errors weigh more than in MAESST: the SSE of the flat line ŷ = ȳ, the best guess without a featurePart 2
The notebook, and the milestone of this week
https://colab.research.google.com/github/
tirthajyoti/Machine-Learning-with-Python/blob/
master/Regression/Linear_Regression_Practice.ipynburl = ("https://raw.githubusercontent.com/"
"tirthajyoti/Machine-Learning-with-Python/"
"master/Datasets/USA_Housing.csv")
df = pd.read_csv(url)
df.info(verbose=True)5000 non-null: no missing valuesPriceAddress is text: a linear model only multiplies numbers, so it stays out of Xdf['Price'].plot.hist(bins=25, figsize=(8,4))1e6 under the axis: the ticks are in millions
df.corr(numeric_only=True)
sns.heatmap(df.corr(numeric_only=True),
annot=True, linewidths=2)
| Feature | Correlation with Price |
|---|---|
| Avg. Area Income | 0.640 |
| Avg. Area House Age | 0.453 |
| Area Population | 0.409 |
| Avg. Area Number of Rooms | 0.336 |
| Avg. Area Number of Bedrooms | 0.171 |
Part 3
LinearRegression in scikit-learn
X = df[l_column[0:len_feature-2]] # 5 features
y = df[l_column[len_feature-2]] # Price
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=123)sklearn.cross_validation, which no longer exists: use sklearn.model_selection.lm = LinearRegression()
lm.fit(X_train, y_train)
print(lm.intercept_)
cdf = pd.DataFrame(data=lm.coef_,
index=X_train.columns,
columns=['Coefficients'])| Feature | Coefficient |
|---|---|
| Income | 21.597602 |
| House age | 165201.104954 |
| Rooms | 119061.463868 |
| Bedrooms | 3212.585606 |
| Population | 15.228121 |
ŷ when its feature grows by 1 and the others stay the sameRow 2648, the first test house. Real price: $800,146.23
| Feature | x | b × x |
|---|---|---|
| Income | 63824.394539 | 1,378,453.87 |
| House age | 4.991750 | 824,642.62 |
| Rooms | 5.003836 | 595,764.04 |
| Bedrooms | 4.00 | 12,850.34 |
| Population | 40086.458749 | 610,441.44 |
The notebook divides each coefficient by its standard error: the t-statistic
| Feature | t-statistic |
|---|---|
| Avg. Area Income | 134.68 |
| Avg. Area House Age | 95.91 |
| Area Population | 89.64 |
| Avg. Area Number of Rooms | 70.18 |
| Avg. Area Number of Bedrooms | 2.33 |
Part 4
Predict the 1500 test houses
predictions = lm.predict(X_test)
plt.scatter(x=y_test, y=predictions)predictions: 1500 prices, one per test house


Mean absolute error (MAE): 81739.77482718184
Mean square error (MSE): 10489638335.804983
Root mean square error (RMSE): 102418.93543581179
R-squared value of predictions: 0.919| Measure | Value | Meaning |
|---|---|---|
| MAE | $81,740 | average size of an error |
| RMSE | $102,419 | typical error, about 8% of the mean price |
| Test R² | 0.919 | about 92% of the price spread explained |
| Training R² | 0.917 | as good on new houses as on seen ones |
Before you practise
cross_validation, df.corr() with a text column, distplot./Datasets/USA_Housing.csv in ColabAddress in XYour team project
shape, the columns and the types with info()isnull().sum(), then fillna or dropna (week 1)describe() and look for impossible valuesnumeric_only=TruePart 5
About 30 minutes, answers follow each task
About 10 minutes
| Area | x (income, $10,000) | y (price, $100,000) |
|---|---|---|
| A1 | 4 | 6 |
| A2 | 5 | 7 |
| A3 | 6 | 10 |
| A4 | 7 | 11 |
| A5 | 8 | 11 |
x̄, ȳ, the slope b₁ and the intercept b₀Answers
Answers
| Area | ŷ | e | e² |
|---|---|---|---|
| A1 | 6.2 | -0.2 | 0.04 |
| A2 | 7.6 | -0.6 | 0.36 |
| A3 | 9.0 | 1.0 | 1.00 |
| A4 | 10.4 | 0.6 | 0.36 |
| A5 | 11.8 | -0.8 | 0.64 |
About 5 minutes
Row 2456, real price $707,345.06, intercept -2,631,028.90. Predict, then find the residual.
| Feature | x | Coefficient b |
|---|---|---|
| Income | 67041.967661 | 21.597602 |
| House age | 6.021458 | 165201.104954 |
| Rooms | 5.346830 | 119061.463868 |
| Bedrooms | 3.39 | 3212.585606 |
| Population | 15633.099048 | 15.228121 |
Answers
About 5 minutes
About 10 minutes
lm1 on X_train[['Avg. Area Income']] only: print intercept, coefficient, test R², MAE, RMSEAvg. Area Number of Bedrooms (drop(..., axis=1)) and print its test R²Answers
| Model | Test R² | Test RMSE |
|---|---|---|
| All five features | 0.919 | 102,418.94 |
| Income only | 0.417 | 275,407.48 |
| All except bedrooms | 0.920 | 102,282.54 |
b0 plus a weighted sum of the featuresy − ŷ; least squares makes the sum of their squares smallestMahmoud Abas|Linear Regression