A real estate agent wants help predicting housing prices for regions in the USA. Let us create a model for her that allows to put in a few features of a house and returns back an estimate of what the house would sell for.
Linear Regression might be a good path to solve this problem!
You have some information about a bunch of houses in regions of the United States,it is all in the data set: USA_Housing.csv.
The data contains the following columns:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
USAhousing = pd.read_csv('USA_Housing.csv')
USAhousing.head()
USAhousing.info()
USAhousing.describe()
USAhousing.columns
Let's create some simple plots to check out the data!
sns.pairplot(USAhousing)
sns.distplot(USAhousing['Price'])
sns.heatmap(USAhousing.corr())
Let's now begin to train out regression model. We will need to first split up our data into an X array that contains the features to train on, and a y array with the target variable, in this case the Price column. We will toss out the Address column because it only has text info that the linear regression model can't use.
X = USAhousing[['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area Number of Rooms',
'Avg. Area Number of Bedrooms', 'Area Population']]
y = USAhousing['Price']
Now let's split the data into a training set and a testing set. We will train out model on the training set and then use the test set to evaluate the model.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=101)
from sklearn.linear_model import LinearRegression
lm = LinearRegression()
lm.fit(X_train,y_train)
Let's evaluate the model by checking out it's coefficients and how we can interpret them.
# print the intercept
print(lm.intercept_)
coeff_df = pd.DataFrame(lm.coef_,X.columns,columns=['Coefficient'])
coeff_df
Interpreting the coefficients:
Let's grab predictions off our test set and see how well it did!
predictions = lm.predict(X_test)
plt.scatter(y_test,predictions)
Here are three common evaluation metrics for regression problems:
Mean Absolute Error (MAE) is the mean of the absolute value of the errors:
$$\frac 1n\sum_{i=1}^n|y_i-\hat{y}_i|$$
Comparing these metrics:
from sklearn import metrics
print('MAE:', metrics.mean_absolute_error(y_test, predictions))