Linear regression (i.e. ordinary least squares) is one of the most commonly used statistical modeling technique. It works wonderfully in many situations, but there are scenarios in which we want the coefficients to be non-negative (e.g. where we don't want the prediction to be negative. For example, if we are predicting price of something, and negative price would not make sense in that application).
In this example, we turn to something called non-linear least squares (nnls) regression. We will not go into the mathematical details of this model. A few resources are listed below if you are interested in a deeper dive.
I will note that nnls approximates linear regression, and the performance of this model will always be worse than linear regression. There is a cost to putting constraints on the coefficients of a linear model, and we explore that too in the example below.
First we import a the boston house prices dataset, and print a description of it so we can examine what is in the data. Remember in order to execute a 'cell' like the one below, you can 1) click on it and run it using the run button above or 2) click in the cell and hit shift+enter.
import pandas as pd
from sklearn.datasets import load_boston
boston = load_boston()
print(boston.data.shape) #get (numer of rows, number of columns or 'features')
print(boston.DESCR) #get a description of the dataset
data = pd.DataFrame(boston.data, columns=boston.feature_names)
data.head()
#For some reason, the loaded data does not include the target variable (MEDV), we add it here
data['MEDV'] = pd.Series(data=boston.target, index=data.index)
data.describe() #get some basic stats on the dataset
#Load the independent variables (the x1, x2, etc.) into a dataframe object called 'X'. Similarly for the dependent variable 'Y'
X = data.drop('MEDV', axis = 1) #define independent predictor set (excluding the dependent variable)
Y = data['MEDV'] #define the target values (i.e. the dependent variable)
We randomly select a third of our data to be the 'test' dataset. This way we can train our model on 2/3 of the data, and test it on the remainder. Once we are confident that our model is generalizing well (i.e. there is not a HUGE different in the training/testing performance, or in other words, not obviously overfitting), then we can use all of our data to train 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.33, random_state = 5)
print(X_train.shape)
print(X_test.shape)
print(Y_train.shape)
print(Y_test.shape)
In linear regression we assume that the relationship between the independent variables (X) and the dependent variable (Y) is linear and then go about finding one that minimizes the squared error between the predicted Y and the actual Y.
$$ {y}_i = \beta_0 + \beta_1 {x}_i + \epsilon_i $$We now import the LinearRegression method from the sklearn library. Note that the process of creating the model involves the very simple command lm.fit(X,Y). This runs the model and we find the intercept-term, $\beta_0$, and the coefficient $\beta_1$ that minimizes the squared errors.
from sklearn.linear_model import LinearRegression
lm = LinearRegression()
lm.fit(X_train,Y_train)
Y_pred_train = lm.predict(X_train) #predictions on training data
Y_pred = lm.predict(X_test) #predictions on testing data
# We plot predicted Y (y-axis) against actual Y (x-axis). Perfect predictions will lie on the diagonal. We see the diagonal trend, suggesting a 'good' fit
import matplotlib.pyplot as plt
plt.scatter(Y_test,Y_pred)
plt.xlabel("Actual Price: $Y_i$")
plt.ylabel("Predicted Price: $\hat{Y}_i$")
plt.title("Predicted Price vs Actual Price: $Y_i$ vs $\hat{Y}_i$")
plt.show()
#Let's get the coefficients - observe that some are significantly negative
print('Intercept term: ',lm.intercept_) # This gives us the intercept term
print('Coefficients: \n',lm.coef_) # This gives us the coefficients (in the case of this model, just one coefficient)
NNLS is a technique in mathematical optimization where we don't allow the regression coefficients to become negative. We still want to minimize the squared error. That is, given a matrix X and a column vector of dependent Y, the goal is to find:
$$ \textrm{arg min}_{b} \mid\mid \textbf{Xb - Y} \mid\mid_{2} \textrm{subject to b}\geq0 \\ \textit{where } \mid\mid \textbf{.} \mid\mid_{2} \textit{is the euclidean norm} $$from scipy.optimize import nnls
Coef_nnls, rnorm =nnls(X_train.to_numpy(), Y_train.to_numpy(), maxiter=1000)
Coef_nnls
import numpy as np
#Merge stuff
Train_Data=X_train.copy()
Train_Data['MEDV']=Y_train
Train_Data['Y_pred']=Y_pred_train
Train_Data.head()
C1=np.array(pd.DataFrame(Coef_nnls).iloc[0])
C2=np.array(pd.DataFrame(Coef_nnls).iloc[1])
C3=np.array(pd.DataFrame(Coef_nnls).iloc[2])
C4=np.array(pd.DataFrame(Coef_nnls).iloc[3])
C5=np.array(pd.DataFrame(Coef_nnls).iloc[4])
C6=np.array(pd.DataFrame(Coef_nnls).iloc[5])
C7=np.array(pd.DataFrame(Coef_nnls).iloc[6])
C8=np.array(pd.DataFrame(Coef_nnls).iloc[7])
C9=np.array(pd.DataFrame(Coef_nnls).iloc[8])
C10=np.array(pd.DataFrame(Coef_nnls).iloc[9])
C11=np.array(pd.DataFrame(Coef_nnls).iloc[10])
C12=np.array(pd.DataFrame(Coef_nnls).iloc[11])
C13=np.array(pd.DataFrame(Coef_nnls).iloc[12])
Train_Data['Y_nnls']=C1*Train_Data['CRIM']+C2*Train_Data['ZN']+C3*Train_Data['INDUS']+C4*Train_Data['CHAS']+C5*Train_Data['NOX']+C6*Train_Data['RM']+C7*Train_Data['AGE']+C8*Train_Data['DIS']+C9*Train_Data['RAD']+C10*Train_Data['TAX']+C11*Train_Data['PTRATIO']+C12*Train_Data['B']+C13*Train_Data['LSTAT']
Train_Data
We measure the accuracy of NNLS approach using R-squared metric, and compare it to linear regression. Note the large degradation in performance in this example. A large degradation in performance is by no means a given. For large and complex datasets, the performance can often be quite close to linear regression - just something you have to test out when considering the benefits of NNLS.
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
rsq = r2_score(Y_train,Y_pred_train) #R-Squared on the training data
print('R-square, Linear Regression: ',rsq)
rsq = r2_score(Train_Data['MEDV'],Train_Data['Y_pred']) #R-Squared from least-squares regression
print('R-square, Linear Regression: ',rsq)
rsq = r2_score(Train_Data['MEDV'],Train_Data['Y_nnls']) #R-Squared from nnls
print('R-square, NNLS: ',rsq)
You can compare this example to the OLS method: https://predictivemodeler.com/2019/08/19/py-ols-boston-house-prices/
If you have ideas on how to improve this post, please let me know: https://predictivemodeler.com/feedback/