AdSense

Showing posts with label Linear Regression. Show all posts
Showing posts with label Linear Regression. Show all posts

Saturday, May 30, 2020

Multiple Linear Regression in Python (Training Data, Predictive Model Building by Training Data, Test Data, and Model Predictions for Test Data)

Multiple Linear Regression in Python (Training Data, Predictive Model Building by Training Data, Test Data, and Model Predictions for Test Data) 



0_MacOS_Python_setup.txt
# Install on Terminal of MacOS

# 1. pandas
#pip3 install -U pandas

# 2. matplotlib, from mpl_toolkits.mplot3d import Axes3D
#pip3 install -U matplotlib

# 3. scikit-learn (sklearn)
#pip3 install -U scikit-learn

# 4. statsmodels
#pip3 install -U statsmodels

# 5. tkinter
#pip3 install -U tkinter

# 6. NumPy
#pip3 install -U numpy

# 7. seaborn
#pip3 install -U seaborn



1_MacOS_Terminal.txt
########## Run Terminal on MacOS and execute
### TO UPDATE
cd "YOUR_WORKING_DIRECTORY"


python3 lrm03.py training.csv test.csv




Data files



training.csv
Year,Month,x1,x2,y
2017,12,2.75,5.3,1464.00
2017,11,2.5,5.3,1394.00
2017,10,2.5,5.3,1357.00
2017,9,2.5,5.3,1293.00
2017,8,2.5,5.4,1256.00
2017,7,2.5,5.6,1254.00
2017,6,2.5,5.5,1234.00
2017,5,2.25,5.5,1195.00
2017,4,2.25,5.5,1159.00
2017,3,2.25,5.6,1167.00
2017,2,2,5.7,1130.00
2017,1,2,5.9,1075.00
2016,12,2,6,1047.00
2016,11,1.75,5.9,965.00
2016,10,1.75,5.8,943.00
2016,9,1.75,6.1,958.00
2016,8,1.75,6.2,971.00
2016,7,1.75,6.1,949.00
2016,6,1.75,6.1,884.00
2016,5,1.75,6.1,866.00
2016,4,1.75,5.9,876.00
2016,3,1.75,6.2,822.00
2016,2,1.75,6.2,704.00
2016,1,1.75,6.1,719.00



test.csv
Year,Month,x1,x2,y
2019,12,3.75,4.5,1831.75
2019,11,3.5,4.5,1744.17
2019,10,3.5,4.7,1697.88
2019,9,3.5,4.7,1786.3
2019,8,3.25,4.8,1735.18
2019,7,3.25,4.8,1732.42
2019,6,3.25,4.7,1704.79
2019,5,3.25,4.7,1650.91
2019,4,3.25,4.7,1601.18
2019,3,3.25,4.8,1612.23
2019,2,3,4.9,1561.11
2019,1,3,4.9,1485.13
2018,12,3,5,1446.45
2018,11,3,4.9,1580.77
2018,10,3,4.8,1544.73
2018,9,3,5.1,1569.3
2018,8,3,5.2,1590.6
2018,7,3,5.1,1554.56
2018,6,3,5.3,1586.29
2018,5,3,5.3,1553.99
2018,4,2.75,5.1,1571.93
2018,3,2.75,5.4,1475.03
2018,2,2.75,5.4,1404.79
2018,1,2.75,5.3,1434.72




Python files

lrm03.py
########## Multiple Linear Regression in Python (Training Data, Predictive Model Building by Training Data, Test Data, and Model Predictions for Test Data) ##########
#
# Run this script on Terminal of MacOS as follows:
# python3 lrm01.py training.csv test.csv
#
# Reference:
# Example of Multiple Linear Regression in Python
# https://datatofish.com/multiple-linear-regression-python/



##### Checking for Linearity

import pandas as pd
import matplotlib.pyplot as plt
import sys
import numpy as np
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D


###training.csv
trainingcsv = sys.argv[1]    # the first argument after lrm01.py
#
# 'y' (dependent variable) : e.g., Stock_Index_Price
# 'x1' (independent variable 1) : e.g., Interest_Rate
# 'x2' (independent variable 2) : e.g., Unemployment_Rate
#
#
#trainingcsv = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
#                'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
#                'x1': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
#                'x2': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
#                'y': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]      
#                }
#
#df = pd.DataFrame(trainingcsv,columns=['Year','Month','x1','x2','y'])


###test.csv
testcsv = sys.argv[2]    # the second argument after lrm01.py


### Read csv files
#
#training data
dftmp = pd.read_csv(trainingcsv, index_col=0)
#dfnp = dftmp.values    #covert pandas to numpy.ndarray
df = dftmp
#
#
#test data
dftesttmp = pd.read_csv(testcsv, index_col=0)
#dftestnp = dftesttmp.values    #covert pandas to numpy.ndarray
dftest = dftesttmp


### plot 1: Training Data y and x1
#
# 'y' (dependent variable) : e.g., Stock_Index_Price
# 'x1' (independent variable 1) : e.g., Interest_Rate
#
plt.scatter(df['x1'], df['y'], color='red', label="Training Data y and x1")
plt.legend()
plt.title('y vs x1', fontsize=14)
plt.xlabel('x1', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.grid(True)
plt.savefig("Figure_1_y_x1_training.png")    # added to save a figure
plt.show()


### plot 2: Training Data y and x2
#
# 'y' (dependent variable) : e.g., Stock_Index_Price
# 'x2' (independent variable 2) : e.g., Unemployment_Rate
#
plt.scatter(df['x2'], df['y'], color='green', label="Training Data y and x2")
plt.legend()
plt.title('y vs x2', fontsize=14)
plt.xlabel('x2', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.grid(True)
plt.savefig("Figure_2_y_x2_training.png")    # added to save a figure
plt.show()


### plot 3: Test Data y and x1
#
# 'y' (dependent variable) : e.g., Stock_Index_Price
# 'x1' (independent variable 1) : e.g., Interest_Rate
#
plt.scatter(dftest['x1'], dftest['y'], color='red', label="Test Data y and x1")
plt.legend()
plt.title('y vs x1', fontsize=14)
plt.xlabel('x1', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.grid(True)
plt.savefig("Figure_3_y_x1_test.png")    # added to save a figure
plt.show()


### plot 4: Test Data y and x2
#
# 'y' (dependent variable) : e.g., Stock_Index_Price
# 'x2' (independent variable 2) : e.g., Unemployment_Rate
#
plt.scatter(dftest['x2'], dftest['y'], color='green', label="Test Data y and x2")
plt.legend()
plt.title('y vs x2', fontsize=14)
plt.xlabel('x2', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.grid(True)
plt.savefig("Figure_4_y_x2_test.png")    # added to save a figure
plt.show()



##### Performing the Multiple Linear Regression (for Training Data)

from sklearn import linear_model
import statsmodels.api as sm


X = df[['x1','x2']]
Y = df['y']


### with sklearn
regr = linear_model.LinearRegression()
regr.fit(X, Y)

print('\n')
print('==============================')
print('Prediction model (for Training Data): \n')
print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)


with open('coef.txt', 'w') as f:
  print('Intercept: ' + str(regr.intercept_), file=f)
  print('Coefficients:' + str(regr.coef_), file=f)



### with statsmodels
X = sm.add_constant(X) # adding a constant
#
# X: raw training data that has const=1, x1, and x2.
pd.DataFrame(data=X).to_csv("X.csv", header=True, index=False)


model = sm.OLS(Y, X).fit()
predictions = model.predict(X)
#
# YPRED
#     y      : raw data Y
#     y_pred : predicted data by using raw training data x1 and x2 plus intercentpt.
YYPRED = pd.concat([Y, predictions], axis=1).rename(columns={0: 'y_pred'})
pd.DataFrame(data=YYPRED).to_csv("YYPRED.csv", header=True, index=False)
#
#resultstmp have: y, y_pred, const, x1, and x2; all data except for y_pred & const=1 are raw training data
resultstmp = pd.concat([YYPRED, X], axis=1)
#print(resultstmp)
resultstmp.to_csv("resultstmp.csv", header=True, index=False)
#
resultsint = pd.Series(regr.intercept_, index=resultstmp.index, name='coef_const')
resultscoef1 = pd.Series(regr.coef_[0], index=resultstmp.index, name='coef_x1')
resultscoef2 = pd.Series(regr.coef_[1], index=resultstmp.index, name='coef_x2')
#
pd.DataFrame(data=resultsint).to_csv("resultsint.csv", header=True, index=False)
pd.DataFrame(data=resultscoef1).to_csv("resultscoef1.csv", header=True, index=False)
pd.DataFrame(data=resultscoef2).to_csv("resultscoef2.csv", header=True, index=False)
#
RESULTS = pd.concat([resultstmp, resultsint, resultscoef1, resultscoef2], axis=1)
RESULTS.to_csv("RESULTS.csv", header=True, index=False)
# See "RESULTS.csv"
# y, y_pred, const, x1, x2, coef_const, coef_x1, and coef_x2; the last three were coefficients for intercept, x1, and x2, respectively.
#
# For instance,
# y_pred (B2) = F2*C2 + G2*D2 + H2*E2
# y_pred (B2) = coef_const(F2)*const(C2) + coef_1(G2)*x1(D2) + coef_1(H2)*x2(E2)
# 1422.862389 = 1798.403978*1 + 345.540087*2.75 + (-250.1465714)*5.3


print_model = model.summary()
print(print_model)


'''
Intercept:
 1798.4039776258546
Coefficients:
 [ 345.54008701 -250.14657137]
Predicted y:
 [1422.86238865]
                            OLS Regression Results                          
==============================================================================
Dep. Variable:      Stock_Index_Price   R-squared:                       0.898
Model:                            OLS   Adj. R-squared:                  0.888
Method:                 Least Squares   F-statistic:                     92.07
Date:                Fri, 29 May 2020   Prob (F-statistic):           4.04e-11
Time:                        08:43:16   Log-Likelihood:                -134.61
No. Observations:                  24   AIC:                             275.2
Df Residuals:                      21   BIC:                             278.8
Df Model:                           2                                        
Covariance Type:            nonrobust                                        
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const       1798.4040    899.248      2.000      0.059     -71.685    3668.493
x1           345.5401    111.367      3.103      0.005     113.940     577.140
x2          -250.1466    117.950     -2.121      0.046    -495.437      -4.856
==============================================================================
Omnibus:                        2.691   Durbin-Watson:                   0.530
Prob(Omnibus):                  0.260   Jarque-Bera (JB):                1.551
Skew:                          -0.612   Prob(JB):                        0.461
Kurtosis:                       3.226   Cond. No.                         394.
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

'''


##### Applying the Multiple Linear Regression (to Test Data)

#from sklearn import linear_model
#import statsmodels.api as sm


XTEST = dftest[['x1','x2']]
YTEST = dftest['y']


### with statsmodels
XTEST = sm.add_constant(XTEST) # adding a constant
#
# XTEST: raw test data that has const=1, x1, and x2.
pd.DataFrame(data=XTEST).to_csv("XTEST.csv", header=True, index=False)


#modeltest = sm.OLS(YTEST, XTEST).fit()    # Test Data is not used to build a model.
#predictionstest = modeltest.predict(XTEST)    # Test Data is not used to build a model.
predictionstest = model.predict(XTEST)
#
# YTESTPRED
#     y      : raw data YTEST
#     y_pred : predicted data by using raw training data x1 and x2 plus intercept.
YYPREDTEST = pd.concat([YTEST, predictionstest], axis=1).rename(columns={0: 'y_pred'})
pd.DataFrame(data=YYPREDTEST).to_csv("YYPREDTEST.csv", header=True, index=False)
#
resultstmptest = pd.concat([YYPREDTEST, XTEST], axis=1)
#
resultstmptest.to_csv("resultstmptest.csv", header=True, index=False)
#
resultsinttest = pd.Series(regr.intercept_, index=resultstmptest.index, name='coef_const')
pd.DataFrame(data=resultsinttest).to_csv("resultsinttest.csv", header=True, index=False)
#
resultscoef1test = pd.Series(regr.coef_[0], index=resultstmptest.index, name='coef_x1')
pd.DataFrame(data=resultscoef1test).to_csv("resultscoef1test.csv", header=True, index=False)
#
resultscoef2test = pd.Series(regr.coef_[1], index=resultstmptest.index, name='coef_x2')
pd.DataFrame(data=resultscoef2test).to_csv("resultscoef2test.csv", header=True, index=False)
#


pd.concat([resultstmptest, resultsinttest, resultscoef1test, resultscoef2test], axis=1)

RESULTSTEST = pd.concat([resultstmptest, resultsinttest, resultscoef1test, resultscoef2test], axis=1)
RESULTSTEST.to_csv("RESULTSTEST.csv", header=True, index=False)



##### 3D plot


###Training Data: df (y, x1, x2)
XXX = df[['x1']]
YYY = df[['x2']]
ZZZ = df['y']


### Predictions (y_pred) and Training Data (y, x1, x2)
ZZZPRED = YYPRED['y_pred']


### Test Data: dftest (y, x1, x2)
XXXTEST = dftest[['x1']]
YYYTEST = dftest[['x2']]
ZZZTEST = dftest['y']


### Predictions (y_pred) and Test Data (y, x1, x2); Test Data is not used to build a predictive model
ZZZPREDTEST = YYPREDTEST['y_pred']



###graph
sns.set_style("darkgrid")
#
#frames of a graph
fig = plt.figure()
ax = Axes3D(fig)
#
#axis labels
ax.set_xlabel("X1")
ax.set_ylabel("X2")
ax.set_zlabel("Y")


###plot
##linestyle='None' means no line
#
# Training Data (y, x1, x2)
ax.plot(XXX,YYY,ZZZ, marker="o",linestyle='None', label='Training Data (y, x1, x2)')
#
# Predictions (y_pred) and Training Data (x1, x2)
ax.plot(XXX,YYY,ZZZPRED, marker="*", linestyle='None', label='Predictions (y_pred) and Training Data (x1, x2)')
#
# Test Data (y, x1, x2)
ax.plot(XXXTEST,YYYTEST,ZZZTEST, marker="+", linestyle='None', label='Test Data (y, x1, x2)')
#
# Predictions (y_pred) and Test Data (x1, x2)
ax.plot(XXXTEST,YYYTEST,ZZZPREDTEST, marker="x", linestyle='None', label='Predictions (y_pred) and Test Data (x1, x2); Test Data is not used to build a predictive model')


ax.legend()


###show a prediction equation on the plot
#
minx = min(XXX.min()[0],XXXTEST.min()[0])
miny = min(YYY.min()[0], YYYTEST.min()[0])
minz = min(ZZZ.min(), ZZZPRED.min(), ZZZTEST.min(), ZZZPREDTEST.min())
#
ax.text(minx + (abs(minx) * 0.05), miny + (abs(miny) * 0.05), minz + (abs(minz) * 0.05), 'y_pred (Training Data) = ' + str(np.round(regr.intercept_, decimals=2)) + ' + (' + str(np.round(regr.coef_[0], decimals=2)) + '* x1) + (' + str(np.round(regr.coef_[1], decimals=2)) + '* x2)', color='black')
ax.text(minx, miny, minz, 'y_pred (Test Data)     = ' + str(np.round(regr.intercept_, decimals=2)) + ' + (' + str(np.round(regr.coef_[0], decimals=2)) + '* x1) + (' + str(np.round(regr.coef_[1], decimals=2)) + '* x2)', color='black')


plt.savefig("Figure_5_y_x1_x2_y_pred_training_data_n_predictive_model_results_and_test_data_n_model_predications.png")    # added to save a figure
plt.show()




Figures
Figure_1_y_x1_training.png


Figure_2_y_x2_training.png

Figure_3_y_x1_test.png


Figure_4_y_x2_test.png


Figure_3_y_x1_x2_y_pred_training_data_n_predictive_model_results_and_test_data_n_model_predications






References

Example of Multiple Linear Regression in Python

Friday, May 29, 2020

Multiple Linear Regression in Python (Predictions by Training Data and Test Data)

Multiple Linear Regression in Python (Predictions by Training Data and Test Data) 



0_MacOS_Python_setup.txt
# Install on Terminal of MacOS

# 1. pandas
#pip3 install -U pandas

# 2. matplotlib, from mpl_toolkits.mplot3d import Axes3D
#pip3 install -U matplotlib

# 3. scikit-learn (sklearn)
#pip3 install -U scikit-learn

# 4. statsmodels
#pip3 install -U statsmodels

# 5. tkinter
#pip3 install -U tkinter

# 6. NumPy
#pip3 install -U numpy

# 7. seaborn
#pip3 install -U seaborn



1_MacOS_Terminal.txt
########## Run Terminal on MacOS and execute
### TO UPDATE
cd "YOUR_WORKING_DIRECTORY"


python3 lrm02.py training.csv test.csv




Data files



training.csv
Year,Month,x1,x2,y
2017,12,2.75,5.3,1464.00
2017,11,2.5,5.3,1394.00
2017,10,2.5,5.3,1357.00
2017,9,2.5,5.3,1293.00
2017,8,2.5,5.4,1256.00
2017,7,2.5,5.6,1254.00
2017,6,2.5,5.5,1234.00
2017,5,2.25,5.5,1195.00
2017,4,2.25,5.5,1159.00
2017,3,2.25,5.6,1167.00
2017,2,2,5.7,1130.00
2017,1,2,5.9,1075.00
2016,12,2,6,1047.00
2016,11,1.75,5.9,965.00
2016,10,1.75,5.8,943.00
2016,9,1.75,6.1,958.00
2016,8,1.75,6.2,971.00
2016,7,1.75,6.1,949.00
2016,6,1.75,6.1,884.00
2016,5,1.75,6.1,866.00
2016,4,1.75,5.9,876.00
2016,3,1.75,6.2,822.00
2016,2,1.75,6.2,704.00
2016,1,1.75,6.1,719.00



test.csv
Year,Month,x1,x2,y
2019,12,3.75,4.5,1831.75
2019,11,3.5,4.5,1744.17
2019,10,3.5,4.7,1697.88
2019,9,3.5,4.7,1786.3
2019,8,3.25,4.8,1735.18
2019,7,3.25,4.8,1732.42
2019,6,3.25,4.7,1704.79
2019,5,3.25,4.7,1650.91
2019,4,3.25,4.7,1601.18
2019,3,3.25,4.8,1612.23
2019,2,3,4.9,1561.11
2019,1,3,4.9,1485.13
2018,12,3,5,1446.45
2018,11,3,4.9,1580.77
2018,10,3,4.8,1544.73
2018,9,3,5.1,1569.3
2018,8,3,5.2,1590.6
2018,7,3,5.1,1554.56
2018,6,3,5.3,1586.29
2018,5,3,5.3,1553.99
2018,4,2.75,5.1,1571.93
2018,3,2.75,5.4,1475.03
2018,2,2.75,5.4,1404.79
2018,1,2.75,5.3,1434.72




Python files

lrm02.py
########## Multiple Linear Regression in Python (Predictions by Training Data and Test Data) ##########
#
# Run this script on Terminal of MacOS as follows:
# python3 lrm01.py training.csv test.csv
#
# Reference:
# Example of Multiple Linear Regression in Python
# https://datatofish.com/multiple-linear-regression-python/



##### Checking for Linearity

import pandas as pd
import matplotlib.pyplot as plt
import sys
import numpy as np
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D


###training.csv
trainingcsv = sys.argv[1]    # the first argument after lrm01.py
#
# 'y' (dependent variable) : e.g., Stock_Index_Price
# 'x1' (independent variable 1) : e.g., Interest_Rate
# 'x2' (independent variable 2) : e.g., Unemployment_Rate
#
#
#trainingcsv = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
#                'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
#                'x1': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
#                'x2': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
#                'y': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]      
#                }
#
#df = pd.DataFrame(trainingcsv,columns=['Year','Month','x1','x2','y'])


###test.csv
testcsv = sys.argv[2]    # the second argument after lrm01.py


### Read csv files
#
#training data
dftmp = pd.read_csv(trainingcsv, index_col=0)
#dfnp = dftmp.values    #covert pandas to numpy.ndarray
df = dftmp
#
#
#test data
dftesttmp = pd.read_csv(testcsv, index_col=0)
#dftestnp = dftesttmp.values    #covert pandas to numpy.ndarray
dftest = dftesttmp


### plot 1
#
# 'y' (dependent variable) : e.g., Stock_Index_Price
# 'x1' (independent variable 1) : e.g., Interest_Rate
#
plt.scatter(df['x1'], df['y'], color='red', label="Training Data x1")
plt.legend()
plt.title('y vs x1', fontsize=14)
plt.xlabel('x1', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.grid(True)
plt.savefig("Figure_1_y_x1_training.png")    # added to save a figure
plt.show()


### plot 2
#
# 'y' (dependent variable) : e.g., Stock_Index_Price
# 'x2' (independent variable 2) : e.g., Unemployment_Rate
#
plt.scatter(df['x2'], df['y'], color='green', label="Training Data x2")
plt.legend()
plt.title('y vs x2', fontsize=14)
plt.xlabel('x2', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.grid(True)
plt.savefig("Figure_2_y_x2_training.png")    # added to save a figure
plt.show()



##### Performing the Multiple Linear Regression (for Training Data)

from sklearn import linear_model
import statsmodels.api as sm


X = df[['x1','x2']]
Y = df['y']


### with sklearn
regr = linear_model.LinearRegression()
regr.fit(X, Y)

print('\n')
print('==============================')
print('Prediction model (for Training Data): \n')
print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)


with open('coef.txt', 'w') as f:
  print('Intercept: ' + str(regr.intercept_), file=f)
  print('Coefficients:' + str(regr.coef_), file=f)


# prediction with sklearn
#new_x1 = 2.75
#new_x2 = 5.3
#print ('Predicted y: \n', regr.predict([[new_x1 ,new_x2]]))
#print('============================== \n')



### with statsmodels
X = sm.add_constant(X) # adding a constant
#
# X: raw training data that has const=1, x1, and x2.
pd.DataFrame(data=X).to_csv("X.csv", header=True, index=False)


model = sm.OLS(Y, X).fit()
predictions = model.predict(X)
#
# YPRED
#     y      : raw data Y
#     y_pred : predicted data by using raw training data x1 and x2 plus intercentpt.
YYPRED = pd.concat([Y, predictions], axis=1).rename(columns={0: 'y_pred'})
pd.DataFrame(data=YYPRED).to_csv("YYPRED.csv", header=True, index=False)
#
#resultstmp have: y, y_pred, const, x1, and x2; all data except for y_pred & const=1 are raw training data
resultstmp = pd.concat([YYPRED, X], axis=1)
resultstmp.to_csv("resultstmp.csv", header=True, index=False)
#
resultsint = pd.Series(regr.intercept_, index=resultstmp.index, name='coef_const')
resultscoef1 = pd.Series(regr.coef_[0], index=resultstmp.index, name='coef_x1')
resultscoef2 = pd.Series(regr.coef_[1], index=resultstmp.index, name='coef_x2')
#
RESULTS = pd.concat([resultstmp, resultsint, resultscoef1, resultscoef2], axis=1)
RESULTS.to_csv("RESULTS.csv", header=True, index=False)
# See "RESULTS.csv"
# y, y_pred, const, x1, x2, coef_const, coef_x1, and coef_x2; the last three were coefficients for intercept, x1, and x2, respectively.
#
# For instance,
# y_pred (B2) = F2*C2 + G2*D2 + H2*E2
# y_pred (B2) = coef_const(F2)*const(C2) + coef_1(G2)*x1(D2) + coef_1(H2)*x2(E2)
# 1422.862389 = 1798.403978*1 + 345.540087*2.75 + (-250.1465714)*5.3


print_model = model.summary()
print(print_model)


'''
Intercept:
 1798.4039776258546
Coefficients:
 [ 345.54008701 -250.14657137]
Predicted y:
 [1422.86238865]
                            OLS Regression Results                          
==============================================================================
Dep. Variable:      Stock_Index_Price   R-squared:                       0.898
Model:                            OLS   Adj. R-squared:                  0.888
Method:                 Least Squares   F-statistic:                     92.07
Date:                Fri, 29 May 2020   Prob (F-statistic):           4.04e-11
Time:                        08:43:16   Log-Likelihood:                -134.61
No. Observations:                  24   AIC:                             275.2
Df Residuals:                      21   BIC:                             278.8
Df Model:                           2                                        
Covariance Type:            nonrobust                                        
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const       1798.4040    899.248      2.000      0.059     -71.685    3668.493
x1           345.5401    111.367      3.103      0.005     113.940     577.140
x2          -250.1466    117.950     -2.121      0.046    -495.437      -4.856
==============================================================================
Omnibus:                        2.691   Durbin-Watson:                   0.530
Prob(Omnibus):                  0.260   Jarque-Bera (JB):                1.551
Skew:                          -0.612   Prob(JB):                        0.461
Kurtosis:                       3.226   Cond. No.                         394.
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

'''





##### Performing the Multiple Linear Regression (for Test Data)

#from sklearn import linear_model
#import statsmodels.api as sm


XTEST = dftest[['x1','x2']]
YTEST = dftest['y']


### with sklearn
regrtest = linear_model.LinearRegression()
regrtest.fit(XTEST, YTEST)

print('\n')
print('==============================')
print('Prediction model (for Test Data): \n')
print('Intercept: \n', regrtest.intercept_)
print('Coefficients: \n', regrtest.coef_)


with open('coeftest.txt', 'w') as f:
  print('Intercept: ' + str(regrtest.intercept_), file=f)
  print('Coefficients:' + str(regrtest.coef_), file=f)


# prediction with sklearn
#new_x1 = 2.75
#new_x2 = 5.3
#print ('Predicted y: \n', regr.predict([[new_x1 ,new_x2]]))
#print('============================== \n')



### with statsmodels
XTEST = sm.add_constant(XTEST) # adding a constant
#
# XTEST: raw test data that has const=1, x1, and x2.
pd.DataFrame(data=XTEST).to_csv("XTEST.csv", header=True, index=False)


modeltest = sm.OLS(YTEST, XTEST).fit()
predictionstest = modeltest.predict(XTEST)
#
# YTESTPRED
#     y      : raw data YTEST
#     y_pred : predicted data by using raw training data x1 and x2 plus intercentpt.
YYPREDTEST = pd.concat([YTEST, predictionstest], axis=1).rename(columns={0: 'y_pred'})
pd.DataFrame(data=YYPREDTEST).to_csv("YYPREDTEST.csv", header=True, index=False)
#
#resultstmp have: y, y_pred, const, x1, and x2; all data except for y_pred & const=1 are raw training data
resultstmptest = pd.concat([YYPREDTEST, XTEST], axis=1)
resultstmptest.to_csv("resultstmptest.csv", header=True, index=False)
#
resultsinttest = pd.Series(regrtest.intercept_, index=resultstmptest.index, name='coef_const')
resultscoef1test = pd.Series(regrtest.coef_[0], index=resultstmptest.index, name='coef_x1')
resultscoef2test = pd.Series(regrtest.coef_[1], index=resultstmptest.index, name='coef_x2')
#
RESULTSTEST = pd.concat([resultstmptest, resultsinttest, resultscoef1test, resultscoef2test], axis=1)
RESULTSTEST.to_csv("RESULTSTEST.csv", header=True, index=False)
# See "RESULTSTEST.csv"
# y, y_pred, const, x1, x2, coef_const, coef_x1, and coef_x2; the last three were coefficients for intercept, x1, and x2, respectively.
#
# For instance,
# y_pred (B2) = F2*C2 + G2*D2 + H2*E2
# y_pred (B2) = coef_const(F2)*const(C2) + coef_1(G2)*x1(D2) + coef_1(H2)*x2(E2)
# 1422.862389 = 1798.403978*1 + 345.540087*2.75 + (-250.1465714)*5.3


print_model_test = modeltest.summary()
print(print_model_test)


'''
==============================
Prediction model (for Test Data):

Intercept:
 468.67716948165594
Coefficients:
 [375.28267909  -7.11991846]
                            OLS Regression Results                          
==============================================================================
Dep. Variable:                      y   R-squared:                       0.795
Model:                            OLS   Adj. R-squared:                  0.776
Method:                 Least Squares   F-statistic:                     40.77
Date:                Sat, 30 May 2020   Prob (F-statistic):           5.87e-08
Time:                        10:44:30   Log-Likelihood:                -128.11
No. Observations:                  24   AIC:                             262.2
Df Residuals:                      21   BIC:                             265.8
Df Model:                           2                                        
Covariance Type:            nonrobust                                        
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const        468.6772    638.415      0.734      0.471    -858.979    1796.333
x1           375.2827     83.424      4.499      0.000     201.794     548.772
x2            -7.1199     81.061     -0.088      0.931    -175.696     161.456
==============================================================================
Omnibus:                        0.176   Durbin-Watson:                   1.282
Prob(Omnibus):                  0.916   Jarque-Bera (JB):                0.017
Skew:                           0.030   Prob(JB):                        0.992
Kurtosis:                       2.886   Cond. No.                         350.
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

'''







##### 3D plot


###Training Data: df (y, x1, x2)
XXX = df[['x1']]
YYY = df[['x2']]
ZZZ = df['y']


### Predictions (y_pred) by Training Data (y, x1, x2)
ZZZPRED = YYPRED['y_pred']


### Test Data: dftest (y, x1, x2)
XXXTEST = dftest[['x1']]
YYYTEST = dftest[['x2']]
ZZZTEST = dftest['y']


### Predictions (y_pred) by Test Data (y, x1, x2)
ZZZPREDTEST = YYPREDTEST['y_pred']



###graph
sns.set_style("darkgrid")
#
#frames of a graph
fig = plt.figure()
ax = Axes3D(fig)
#
#axis labels
ax.set_xlabel("X1")
ax.set_ylabel("X2")
ax.set_zlabel("Y")


###plot
##linestyle='None' means no line
#
# Training Data
ax.plot(XXX,YYY,ZZZ, marker="o",linestyle='None', label='Training Data')
#
# Predictions (y_pred) by Training Data (y, x1, x2)
ax.plot(XXX,YYY,ZZZPRED, marker="*", linestyle='None', label='Predictions by Training Data')
#
# Test Data
ax.plot(XXXTEST,YYYTEST,ZZZTEST, marker="+", linestyle='None', label='Test Data')
#
# Predictions (y_pred) by Test Data (y, x1, x2)
ax.plot(XXXTEST,YYYTEST,ZZZPREDTEST, marker="x", linestyle='None', label='Predictions by Test Data')


ax.legend()


###show a prediction equation on the plot
#
#print(XXX.min()[0])
#minx = XXX.min()[0]
minx = min(XXX.min()[0],XXXTEST.min()[0])
#
#print(min(YYY.min()[0], YYYTEST.min()[0]))
miny = min(YYY.min()[0], YYYTEST.min()[0])
#
#print(min(ZZZ.min(), ZZZPRED.min(), ZZZTEST.min()))
#minz = min(ZZZ.min(), ZZZPRED.min(), ZZZTEST.min())
minz = min(ZZZ.min(), ZZZPRED.min(), ZZZTEST.min(), ZZZPREDTEST.min())
#
#print('Intercept: \n', regr.intercept_)
#print(type(regr.intercept_))
#<class 'numpy.float64'>
#
#print('Coefficients: \n', regr.coef_)
#print(type(regr.coef_[0]))
#<class 'numpy.float64'>
#print(type(regr.coef_[1]))
#<class 'numpy.float64'>
#
#ax.text(minx, miny, minz, 'y_pred = ' + str(regr.intercept_) + ' + (' + str(regr.coef_[0]) + '* x1) + (' + str(regr.coef_[1]) + '* x2)', color='black')
#ax.text(minx, miny, minz, 'y_pred (Training Data) = ' + str(np.round(regr.intercept_, decimals=2)) + ' + (' + str(np.round(regr.coef_[0], decimals=2)) + '* x1) + (' + str(np.round(regr.coef_[1], decimals=2)) + '* x2)', color='black')
ax.text(minx + (abs(minx) * 0.15), miny + (abs(miny) * 0.15), minz + (abs(minz) * 0.15), 'y_pred (Training Data) = ' + str(np.round(regr.intercept_, decimals=2)) + ' + (' + str(np.round(regr.coef_[0], decimals=2)) + '* x1) + (' + str(np.round(regr.coef_[1], decimals=2)) + '* x2)', color='black')
ax.text(minx, miny, minz, 'y_pred (Test Data)     = ' + str(np.round(regrtest.intercept_, decimals=2)) + ' + (' + str(np.round(regrtest.coef_[0], decimals=2)) + '* x1) + (' + str(np.round(regrtest.coef_[1], decimals=2)) + '* x2)', color='black')


plt.savefig("Figure_3_y_x1_x2_training_n_predicted_and_test_n_predicated.png")    # added to save a figure
plt.show()






Figures
Figure_1_y_x1_training.png


Figure_2_y_x2_training.png


Figure_3_y_x1_x2_training_n_predicted_and_test_n_predicated.png




References

Example of Multiple Linear Regression in Python

Multiple Linear Regression in Python

Multiple Linear Regression in Python



0_MacOS_Python_setup.txt
# Install on Terminal of MacOS

# 1. pandas
#pip3 install -U pandas

# 2. matplotlib, from mpl_toolkits.mplot3d import Axes3D
#pip3 install -U matplotlib

# 3. scikit-learn (sklearn)
#pip3 install -U scikit-learn

# 4. statsmodels
#pip3 install -U statsmodels

# 5. tkinter
#pip3 install -U tkinter

# 6. NumPy
#pip3 install -U numpy

# 7. seaborn
#pip3 install -U seaborn



1_MacOS_Terminal.txt
########## Run Terminal on MacOS and execute
### TO UPDATE
cd "YOUR_WORKING_DIRECTORY"


python3 lrm01.py training.csv test.csv




Data files



training.csv
Year,Month,x1,x2,y
2017,12,2.75,5.3,1464.00
2017,11,2.5,5.3,1394.00
2017,10,2.5,5.3,1357.00
2017,9,2.5,5.3,1293.00
2017,8,2.5,5.4,1256.00
2017,7,2.5,5.6,1254.00
2017,6,2.5,5.5,1234.00
2017,5,2.25,5.5,1195.00
2017,4,2.25,5.5,1159.00
2017,3,2.25,5.6,1167.00
2017,2,2,5.7,1130.00
2017,1,2,5.9,1075.00
2016,12,2,6,1047.00
2016,11,1.75,5.9,965.00
2016,10,1.75,5.8,943.00
2016,9,1.75,6.1,958.00
2016,8,1.75,6.2,971.00
2016,7,1.75,6.1,949.00
2016,6,1.75,6.1,884.00
2016,5,1.75,6.1,866.00
2016,4,1.75,5.9,876.00
2016,3,1.75,6.2,822.00
2016,2,1.75,6.2,704.00
2016,1,1.75,6.1,719.00



test.csv
Year,Month,x1,x2,y
2019,12,3.75,4.5,1831.75
2019,11,3.5,4.5,1744.17
2019,10,3.5,4.7,1697.88
2019,9,3.5,4.7,1786.3
2019,8,3.25,4.8,1735.18
2019,7,3.25,4.8,1732.42
2019,6,3.25,4.7,1704.79
2019,5,3.25,4.7,1650.91
2019,4,3.25,4.7,1601.18
2019,3,3.25,4.8,1612.23
2019,2,3,4.9,1561.11
2019,1,3,4.9,1485.13
2018,12,3,5,1446.45
2018,11,3,4.9,1580.77
2018,10,3,4.8,1544.73
2018,9,3,5.1,1569.3
2018,8,3,5.2,1590.6
2018,7,3,5.1,1554.56
2018,6,3,5.3,1586.29
2018,5,3,5.3,1553.99
2018,4,2.75,5.1,1571.93
2018,3,2.75,5.4,1475.03
2018,2,2.75,5.4,1404.79
2018,1,2.75,5.3,1434.72




Python files

lrm01.py
########## Multiple Linear Regression in Python ##########
#
# Run this script on Terminal of MacOS as follows:
# python3 lrm01.py training.csv test.csv
#
# Reference:
# Example of Multiple Linear Regression in Python
# https://datatofish.com/multiple-linear-regression-python/



##### Checking for Linearity

import pandas as pd
import matplotlib.pyplot as plt
import sys
import numpy as np
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D


###training.csv
trainingcsv = sys.argv[1]    # the first argument after lrm01.py
#
# 'y' (dependent variable) : e.g., Stock_Index_Price
# 'x1' (independent variable 1) : e.g., Interest_Rate
# 'x2' (independent variable 2) : e.g., Unemployment_Rate
#
#
#trainingcsv = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
#                'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
#                'x1': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
#                'x2': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
#                'y': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]      
#                }
#
#df = pd.DataFrame(trainingcsv,columns=['Year','Month','x1','x2','y'])


###test.csv
testcsv = sys.argv[2]    # the second argument after lrm01.py


### Read csv files
#
#training data
dftmp = pd.read_csv(trainingcsv, index_col=0)
#dfnp = dftmp.values    #covert pandas to numpy.ndarray
df = dftmp
#
#
#test data
dftesttmp = pd.read_csv(testcsv, index_col=0)
#dftestnp = dftesttmp.values    #covert pandas to numpy.ndarray
dftest = dftesttmp


### plot 1
#
# 'y' (dependent variable) : e.g., Stock_Index_Price
# 'x1' (independent variable 1) : e.g., Interest_Rate
#
plt.scatter(df['x1'], df['y'], color='red', label="Training Data x1")
plt.legend()
plt.title('y vs x1', fontsize=14)
plt.xlabel('x1', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.grid(True)
plt.savefig("Figure_1_y_x1_training.png")    # added to save a figure
plt.show()


### plot 2
#
# 'y' (dependent variable) : e.g., Stock_Index_Price
# 'x2' (independent variable 2) : e.g., Unemployment_Rate
#
plt.scatter(df['x2'], df['y'], color='green', label="Training Data x2")
plt.legend()
plt.title('y vs x2', fontsize=14)
plt.xlabel('x2', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.grid(True)
plt.savefig("Figure_2_y_x2_training.png")    # added to save a figure
plt.show()



##### Performing the Multiple Linear Regression

from sklearn import linear_model
import statsmodels.api as sm


X = df[['x1','x2']]
Y = df['y']


### with sklearn
regr = linear_model.LinearRegression()
regr.fit(X, Y)

print('\n')
print('==============================')
print('Prediction model: \n')
print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)


with open('coef.txt', 'w') as f:
  print('Intercept: ' + str(regr.intercept_), file=f)
  print('Coefficients:' + str(regr.coef_), file=f)


# prediction with sklearn
#new_x1 = 2.75
#new_x2 = 5.3
#print ('Predicted y: \n', regr.predict([[new_x1 ,new_x2]]))
#print('============================== \n')



### with statsmodels
X = sm.add_constant(X) # adding a constant
#
# X: raw training data that has const=1, x1, and x2.
pd.DataFrame(data=X).to_csv("X.csv", header=True, index=False)


model = sm.OLS(Y, X).fit()
predictions = model.predict(X)
#
# YPRED
#     y      : raw data Y
#     y_pred : predicted data by using raw training data x1 and x2 plus intercentpt.
YYPRED = pd.concat([Y, predictions], axis=1).rename(columns={0: 'y_pred'})
pd.DataFrame(data=YYPRED).to_csv("YYPRED.csv", header=True, index=False)
#
#resultstmp have: y, y_pred, const, x1, and x2; all data except for y_pred & const=1 are raw training data
resultstmp = pd.concat([YYPRED, X], axis=1)
resultstmp.to_csv("resultstmp.csv", header=True, index=False)
#
resultsint = pd.Series(regr.intercept_, index=resultstmp.index, name='coef_const')
resultscoef1 = pd.Series(regr.coef_[0], index=resultstmp.index, name='coef_x1')
resultscoef2 = pd.Series(regr.coef_[1], index=resultstmp.index, name='coef_x2')
#
RESULTS = pd.concat([resultstmp, resultsint, resultscoef1, resultscoef2], axis=1)
RESULTS.to_csv("RESULTS.csv", header=True, index=False)
# See "RESULTS.csv"
# y, y_pred, const, x1, x2, coef_const, coef_x1, and coef_x2; the last three were coefficients for intercept, x1, and x2, respectively.
#
# For instance,
# y_pred (B2) = F2*C2 + G2*D2 + H2*E2
# y_pred (B2) = coef_const(F2)*const(C2) + coef_1(G2)*x1(D2) + coef_1(H2)*x2(E2)
# 1422.862389 = 1798.403978*1 + 345.540087*2.75 + (-250.1465714)*5.3


print_model = model.summary()
print(print_model)


'''
Intercept:
 1798.4039776258546
Coefficients:
 [ 345.54008701 -250.14657137]
Predicted y:
 [1422.86238865]
                            OLS Regression Results                          
==============================================================================
Dep. Variable:      Stock_Index_Price   R-squared:                       0.898
Model:                            OLS   Adj. R-squared:                  0.888
Method:                 Least Squares   F-statistic:                     92.07
Date:                Fri, 29 May 2020   Prob (F-statistic):           4.04e-11
Time:                        08:43:16   Log-Likelihood:                -134.61
No. Observations:                  24   AIC:                             275.2
Df Residuals:                      21   BIC:                             278.8
Df Model:                           2                                        
Covariance Type:            nonrobust                                        
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const       1798.4040    899.248      2.000      0.059     -71.685    3668.493
x1           345.5401    111.367      3.103      0.005     113.940     577.140
x2          -250.1466    117.950     -2.121      0.046    -495.437      -4.856
==============================================================================
Omnibus:                        2.691   Durbin-Watson:                   0.530
Prob(Omnibus):                  0.260   Jarque-Bera (JB):                1.551
Skew:                          -0.612   Prob(JB):                        0.461
Kurtosis:                       3.226   Cond. No.                         394.
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

'''


##### 3D plot


###Training Data: df (y, x1, x2)
XXX = df[['x1']]
YYY = df[['x2']]
ZZZ = df['y']


### Predictions (y_pred) by Training Data (y, x1, x2)
ZZZPRED = YYPRED['y_pred']


### Test Data: dftest (y, x1, x2)
XXXTEST = dftest[['x1']]
YYYTEST = dftest[['x2']]
ZZZTEST = dftest['y']


###graph
sns.set_style("darkgrid")
#
#frames of a graph
fig = plt.figure()
ax = Axes3D(fig)
#
#axis labels
ax.set_xlabel("X1")
ax.set_ylabel("X2")
ax.set_zlabel("Y")


###plot
##linestyle='None' means no line
#
# Training Data
ax.plot(XXX,YYY,ZZZ, marker="o",linestyle='None', label='Training Data')
#
# Predictions (y_pred) by Training Data (y, x1, x2)
ax.plot(XXX,YYY,ZZZPRED, marker="*", linestyle='None', label='Predictions by Training Data')
#
# Test Data
ax.plot(XXXTEST,YYYTEST,ZZZTEST, marker="+", linestyle='None', label='Test Data')

ax.legend()


###show a prediction equation on the plot
#
#print(XXX.min()[0])
minx = XXX.min()[0]
#
#print(min(YYY.min()[0], YYYTEST.min()[0]))
miny = min(YYY.min()[0], YYYTEST.min()[0])
#
#print(min(ZZZ.min(), ZZZPRED.min(), ZZZTEST.min()))
minz = min(ZZZ.min(), ZZZPRED.min(), ZZZTEST.min())
#
#print('Intercept: \n', regr.intercept_)
#print(type(regr.intercept_))
#<class 'numpy.float64'>
#
#print('Coefficients: \n', regr.coef_)
#print(type(regr.coef_[0]))
#<class 'numpy.float64'>
#print(type(regr.coef_[1]))
#<class 'numpy.float64'>
#
#ax.text(minx, miny, minz, 'y_pred = ' + str(regr.intercept_) + ' + (' + str(regr.coef_[0]) + '* x1) + (' + str(regr.coef_[1]) + '* x2)', color='black')
ax.text(minx, miny, minz, 'y_pred = ' + str(np.round(regr.intercept_, decimals=2)) + ' + (' + str(np.round(regr.coef_[0], decimals=2)) + '* x1) + (' + str(np.round(regr.coef_[1], decimals=2)) + '* x2)', color='black')


plt.savefig("Figure_3_y_x1_x2_training_predicted_and_test_data.png")    # added to save a figure
plt.show()






Figures
Figure_1_y_x1_training.png


Figure_2_y_x2_training.png


Figure_3_y_x1_x2_training_predicted_and_test_data.png



References

Example of Multiple Linear Regression in Python

Monday, May 25, 2020

Linear Regression (Fundamentals) in Python

Linear Regression (Fundamentals) in Python



0_MacOS_Python_setup.txt
# Install on Terminal of MacOS

# 1. NumPy
#pip3 install -U numpy

# 2. scikit-learn (sklearn)
#pip3 install -U scikit-learn

# 3.statsmodels
#pip3 install -U statsmodels

#4. matplotlib
#pip3 install -U matplotlib




1_MacOS_Terminal.txt
########## Run Terminal on MacOS and execute
### TO UPDATE
cd "YOUR_WORKING_DIRECTORY"

python3 lrf01.py





Python files

lrf01.py
########## Linear Regression in Python ##########
#
#
# Reference:
#
# Linear Regression in Python
# by Mirko Stojiljkovic
# https://realpython.com/linear-regression-in-python/


##### Regression


### What Is Regression?

#y: The dependent features are called the dependent variables, outputs, or responses.
#x = (x1, x2, ..., xr) where r is the number of inputs: The independent features are called the independent variables, inputs, or predictors.
#
#Regression problems usually have one continuous and unbounded dependent variable. The inputs, however, can be continuous, discrete, or even categorical data such as gender, nationality, brand, and so on.


### When Do You Need Regression?



##### Linear Regression


### Problem Formulation
#
# dependent variable (actual response) 𝑦
# independent variables 𝐱 = (π‘₯₁, …, π‘₯α΅£), where π‘Ÿ is the number of predictors
#
# 𝑦 = 𝛽₀ + 𝛽₁π‘₯₁ + ⋯ + 𝛽ᡣπ‘₯α΅£ + πœ€.
# This equation is the regression equation.
#
# 𝛽₀, 𝛽₁, …, 𝛽ᡣ are the regression coefficients, and πœ€ is the random error.

# estimated regression function 𝑓(𝐱) = 𝑏₀ + 𝑏₁π‘₯₁ + ⋯ + 𝑏ᡣπ‘₯α΅£
# predicted weights: 𝑏₀, 𝑏₁, …, 𝑏ᡣ

# The estimated or predicted response, 𝑓(𝐱ᡒ), for each observation 𝑖 = 1, …, 𝑛,
# should be as close as possible to the corresponding actual response 𝑦ᡒ.
# The differences 𝑦ᡒ - 𝑓(𝐱ᡒ) for all observations 𝑖 = 1, …, 𝑛, are called the residuals.
# Regression is about determining the best predicted weights, that is the weights corresponding to the smallest residuals.

#To get the best weights, you usually minimize the sum of squared residuals (SSR)
# for all observations 𝑖 = 1, …, 𝑛: SSR = Ξ£α΅’(𝑦ᡒ - 𝑓(𝐱ᡒ))².
# This approach is called the method of ordinary least squares.



### Regression Performance

# The coefficient of determination, denoted as 𝑅², tells you which amount of variation in 𝑦 can be explained by the dependence on 𝐱 using the particular regression model. Larger 𝑅² indicates a better fit and means that the model can better explain the variation of the output with different inputs.
#
# The value 𝑅² = 1 corresponds to SSR = 0, that is to the perfect fit since the values of predicted and actual responses fit completely to each other.



### Simple (or Single-Variate) Linear Regression

#The residuals (vertical dashed gray lines) can be calculated as 𝑦ᡒ - 𝑓(𝐱ᡒ) = 𝑦ᡒ - 𝑏₀ - 𝑏₁π‘₯α΅’ for 𝑖 = 1, …, 𝑛.


### Multiple (or Multivariate) Linear Regression

#The estimated regression function is 𝑓(π‘₯₁, …, π‘₯α΅£) = 𝑏₀ + 𝑏₁π‘₯₁ + ⋯ +𝑏ᡣπ‘₯α΅£, and there are π‘Ÿ + 1 weights to be determined when the number of inputs is π‘Ÿ.


### Polynomial Regression
#
# a generalized case of linear regression

# In addition to linear terms like 𝑏₁π‘₯₁, your regression function 𝑓 can include non-linear terms such as 𝑏₂π‘₯₁², 𝑏₃π‘₯₁³, or even 𝑏₄π‘₯₁π‘₯₂, 𝑏₅π‘₯₁²π‘₯₂, and so on.

# Now, remember that you want to calculate 𝑏₀, 𝑏₁, and 𝑏₂, which minimize SSR. These are your unknowns!


### Underfitting and Overfitting


##### Implementing Linear Regression in Python


### Python Packages for Linear Regression

# 1. NumPy
# 2. scikit-learn (sklearn)
# 3.statsmodels



###Simple Linear Regression With scikit-learn


##Step 1: Import packages and classes

import numpy as np
from sklearn.linear_model import LinearRegression


##Step 2: Provide data
#
#arrays
# inputs (regressors, π‘₯)
# output (predictor, 𝑦)
#

x = np.array([5, 15, 25, 35, 45, 55]).reshape((-1, 1))
y = np.array([5, 20, 14, 32, 22, 38])
#You should call .reshape() on x because this array is required to be two-dimensional, or to be more precise, to have one column and as many rows as necessary. That’s exactly what the argument (-1, 1) of .reshape() specifies.

print(x)
#[[ 5]
# [15]
# [25]
# [35]
# [45]
# [55]]

#print(x.shape)
#(6, 1)

print(y)
#[ 5 20 14 32 22 38]

#print(y.shape)
#(6,)


##Step 3: Create a model and fit it

#model = LinearRegression()

# optional parameters to LinearRegression:
#
# - fit_intercept is a Boolean (True by default) that decides whether to calculate the intercept 𝑏₀ (True) or consider it equal to zero (False).
# - normalize is a Boolean (False by default) that decides whether to normalize the input variables (True) or not (False).
# - copy_X is a Boolean (True by default) that decides whether to copy (True) or overwrite the input variables (False).
# - n_jobs is an integer or None (default) and represents the number of jobs used in parallel computation. None usually means one job and -1 to use all processors.

#model.fit(x, y)

#With .fit(), you calculate the optimal values of the weights 𝑏₀ and 𝑏₁, using the existing input and output (x and y) as the arguments.

model = LinearRegression().fit(x, y)
#This statement does the same thing as the previous two.
#
#model = LinearRegression()
#model.fit(x, y)


##Step 4: Get results

#.score()
#coefficient of determination (𝑅²)
# 𝑅² = model.score(predictor x, regressor y)
r_sq = model.score(x, y)
print('coefficient of determination:', r_sq)
#coefficient of determination: 0.7158756137479542

#The attributes of model are
#.intercept_, which represents the coefficient, 𝑏₀ and
#.coef_, which represents 𝑏₁:

print('intercept:', model.intercept_)
#intercept: 5.633333333333329
#.intercept_ is a scalar,

print('slope:', model.coef_)
#slope: [0.54]
#.coef_ is an array


#You should notice that you can provide y as a two-dimensional array as well. In this case, you’ll get a similar result. This is how it might look:

new_model = LinearRegression().fit(x, y.reshape((-1, 1)))
print('intercept:', new_model.intercept_)
#intercept: [5.63333333]
#
print('slope:', new_model.coef_)
#slope: [[0.54]]
#
#.intercept_ is a one-dimensional array with the single element 𝑏₀, and .coef_ is a two-dimensional array with the single element 𝑏₁.


##Step 5: Predict response

y_pred = model.predict(x)
print('predicted response:', y_pred, sep='\n')
#predicted response:
#[ 8.33333333 13.73333333 19.13333333 24.53333333 29.93333333 35.33333333]
#
#print(y)
#[ 5 20 14 32 22 38]

#This is a nearly identical way to predict the response:

y_pred = model.intercept_ + model.coef_ * x
print('predicted response:', y_pred, sep='\n')
#predicted response:
#[[ 8.33333333]
# [13.73333333]
# [19.13333333]
# [24.53333333]
# [29.93333333]
# [35.33333333]]

#The output here differs from the previous example only in dimensions. The predicted response is now a two-dimensional array, while in the previous case, it had one dimension.

#If you reduce the number of dimensions of x to one, these two approaches will yield the same result. You can do this by replacing x with x.reshape(-1), x.flatten(), or x.ravel() when multiplying it with model.coef_.
#
#model2 = LinearRegression().fit(x, y)
#new_model2 = LinearRegression().fit(x, y.reshape((-1, 1)))
#r_sq2 = model2.score(x, y)
#y_pred2 = model.predict(x)
#y_pred2 = model.predict(x.reshape(-1))
#
#y_pred2 = model.intercept_ + model.coef_ * x.reshape(-1)
#print('predicted response:', y_pred2, sep='\n')
#predicted response:
#[ 8.33333333 13.73333333 19.13333333 24.53333333 29.93333333 35.33333333]

#In practice, regression models are often applied for forecasts. This means that you can use fitted models to calculate the outputs based on some other, new inputs:

x_new = np.arange(5).reshape((-1, 1))
print(x_new)
#[[0]
# [1]
# [2]
# [3]
# [4]]
y_new = model.predict(x_new)
print(y_new)
#[5.63333333 6.17333333 6.71333333 7.25333333 7.79333333]



###
#X-Y Plots (scatter plot)
#
import matplotlib.pyplot as plt
#
#x = np.arange(21)
#y = 5 + 2 * x + 2 * np.random.randn(21)
#slope, intercept, r, *__ = scipy.stats.linregress(x, y)
#line = f'Regression line: y={intercept:.2f}+{slope:.2f}x, r={r:.2f}'
#
#matplotlib.axes.Axes.plot
#.plot()
#
#
fig, ax = plt.subplots()
#
#
#Training Data
ax.plot(x, y, linewidth=0, marker='s', label='y')
ax.plot(x, y_pred, label='y_pred')
#ax.plot(x, y_pred, label=line)
#ax.plot(x, intercept + slope * x, label=line)
#
#
#Test Data
ax.plot(x_new, y_new, label='y_new')
#
#
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend(facecolor='white')
plt.savefig("Figure_Simple_Linear_Regression_With_scikit-learn.png")    # added to save a figure
plt.show()
#
###



###Multiple Linear Regression With scikit-learn

##Steps 1 and 2: Import packages and classes, and provide data

import numpy as np
from sklearn.linear_model import LinearRegression

x = [[0, 1], [5, 1], [15, 2], [25, 5], [35, 11], [45, 15], [55, 34], [60, 35]]
y = [4, 5, 20, 14, 32, 22, 38, 43]
x, y = np.array(x), np.array(y)

print(x)
#[[ 0  1]
# [ 5  1]
# [15  2]
# [25  5]
# [35 11]
# [45 15]
# [55 34]
# [60 35]]

print(y)
#[ 4  5 20 14 32 22 38 43]

#In multiple linear regression, x is a two-dimensional array with at least two columns, while y is usually a one-dimensional array. This is a simple example of multiple linear regression, and x has exactly two columns.


##Step 3: Create a model and fit it

model = LinearRegression().fit(x, y)


##Step 4: Get results

r_sq = model.score(x, y)
print('coefficient of determination:', r_sq)
#coefficient of determination: 0.8615939258756776
print('intercept:', model.intercept_)
#intercept: 5.52257927519819
print('slope:', model.coef_)
#slope: [0.44706965 0.25502548]


##Step 5: Predict response

y_pred = model.predict(x)
print('predicted response:', y_pred, sep='\n')
#predicted response:
#[ 5.77760476  8.012953   12.73867497 17.9744479  23.97529728 29.4660957
# 38.78227633 41.27265006]

y_pred = model.intercept_ + np.sum(model.coef_ * x, axis=1)
print('predicted response:', y_pred, sep='\n')

#You can apply this model to new data as well:

x_new = np.arange(10).reshape((-1, 2))
print(x_new)
#[[0 1]
# [2 3]
# [4 5]
# [6 7]
# [8 9]]
y_new = model.predict(x_new)
print(y_new)
#[ 5.77760476  7.18179502  8.58598528  9.99017554 11.3943658 ]




###Polynomial Regression With scikit-learn

#Implementing polynomial regression with scikit-learn is very similar to linear regression. There is only one extra step: you need to transform the array of inputs to include non-linear terms such as π‘₯².


##Step 1: Import packages and classes

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures


##Step 2a: Provide data

x = np.array([5, 15, 25, 35, 45, 55]).reshape((-1, 1))
y = np.array([15, 11, 2, 8, 25, 32])

#Keep in mind that you need the input to be a two-dimensional array. That’s why .reshape() is used.

#print(x)
#[[ 5]
# [15]
# [25]
# [35]
# [45]
# [55]]


##Step 2b: Transform input data

#transformer = PolynomialFeatures(degree=2, include_bias=False)
#
# - degree is an integer (2 by default) that represents the degree of the polynomial regression function.
# - interaction_only is a Boolean (False by default) that decides whether to include only interaction features (True) or all features (False).
# - include_bias is a Boolean (True by default) that decides whether to include the bias (intercept) column of ones (True) or not (False).
#
#transformer.fit(x)
#
#x_ = transformer.transform(x)
#It takes the input array as the argument and returns the modified array.
#
#You can also use .fit_transform() to replace the three previous statements with only one:
x_ = PolynomialFeatures(degree=2, include_bias=False).fit_transform(x)

#modified array
print(x_)
#[[   5.   25.]
# [  15.  225.]
# [  25.  625.]
# [  35. 1225.]
# [  45. 2025.]
# [  55. 3025.]]

#The modified input array contains two columns: one with the original inputs and the other with their squares.

#print(PolynomialFeatures(degree=3, include_bias=False).fit_transform(x))
#[[5.00000e+00 2.50000e+01 1.25000e+02]
# [1.50000e+01 2.25000e+02 3.37500e+03]
# [2.50000e+01 6.25000e+02 1.56250e+04]
# [3.50000e+01 1.22500e+03 4.28750e+04]
# [4.50000e+01 2.02500e+03 9.11250e+04]
# [5.50000e+01 3.02500e+03 1.66375e+05]]
#
#print(5**3)
#125 (=1.25000e+02)


##Step 3: Create a model and fit it

model = LinearRegression().fit(x_, y)
#You should keep in mind that the first argument of .fit() is the modified input array x_ and not the original x.


#Step 4: Get results

r_sq = model.score(x_, y)
print('coefficient of determination:', r_sq)
#coefficient of determination: 0.8908516262498564

print('intercept:', model.intercept_)
#intercept: 21.372321428571425

print('coefficients:', model.coef_)
#coefficients: [-1.32357143  0.02839286]

#include_bias=True instead of include_bias=False
x_ = PolynomialFeatures(degree=2, include_bias=True).fit_transform(x)
# The additional leftmost column containing only ones.
# This column corresponds to the intercept.
print(x_)
#[[1.000e+00 5.000e+00 2.500e+01]
# [1.000e+00 1.500e+01 2.250e+02]
# [1.000e+00 2.500e+01 6.250e+02]
# [1.000e+00 3.500e+01 1.225e+03]
# [1.000e+00 4.500e+01 2.025e+03]
# [1.000e+00 5.500e+01 3.025e+03]]
#
#The first column of x_ contains ones, the second has the values of x, while the third holds the squares of x.

#The intercept is already included with the leftmost column of ones, and you don’t need to include it again when creating the instance of LinearRegression. Thus, you can provide fit_intercept=False. This is how the next statement looks:

model = LinearRegression(fit_intercept=False).fit(x_, y)

r_sq = model.score(x_, y)
print('coefficient of determination:', r_sq)
#coefficient of determination: 0.8908516262498565
print('intercept:', model.intercept_)
#intercept: 0.0
print('coefficients:', model.coef_)
#coefficients: [21.37232143 -1.32357143  0.02839286]
#You see that now .intercept_ is zero, but .coef_ actually contains 𝑏₀ as its first element. Everything else is the same.


##Step 5: Predict response

y_pred = model.predict(x_)
print('predicted response:', y_pred, sep='\n')
#predicted response:
#[15.46428571  7.90714286  6.02857143  9.82857143 19.30714286 34.46428571]

#You can apply the identical procedure if you have several input variables. You’ll have an input array with more than one column, but everything else is the same. Here is an example:

# Step 1: Import packages
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

# Step 2a: Provide data
x = [[0, 1], [5, 1], [15, 2], [25, 5], [35, 11], [45, 15], [55, 34], [60, 35]]
y = [4, 5, 20, 14, 32, 22, 38, 43]
x, y = np.array(x), np.array(y)

# Step 2b: Transform input data
x_ = PolynomialFeatures(degree=2, include_bias=False).fit_transform(x)

# Step 3: Create a model and fit it
model = LinearRegression().fit(x_, y)

# Step 4: Get results
r_sq = model.score(x_, y)
intercept, coefficients = model.intercept_, model.coef_

# Step 5: Predict
y_pred = model.predict(x_)


#This regression example yields the following results and predictions:
#
print('coefficient of determination:', r_sq)
#coefficient of determination: 0.9453701449127822
print('intercept:', intercept)
#intercept: 0.8430556452395734
print('coefficients:', coefficients, sep='\n')
#coefficients:
#[ 2.44828275  0.16160353 -0.15259677  0.47928683 -0.4641851 ]
print('predicted response:', y_pred, sep='\n')
#predicted response:
#[ 0.54047408 11.36340283 16.07809622 15.79139    29.73858619 23.50834636
# 39.05631386 41.92339046]


#In this case, there are six regression coefficients (including the intercept), as shown in the estimated regression function 𝑓(π‘₯₁, π‘₯₂) = 𝑏₀ + 𝑏₁π‘₯₁ + 𝑏₂π‘₯₂ + 𝑏₃π‘₯₁² + 𝑏₄π‘₯₁π‘₯₂ + 𝑏₅π‘₯₂².



###Advanced Linear Regression With statsmodels

##Step 1: Import packages

import numpy as np
import statsmodels.api as sm


##Step 2: Provide data and transform inputs

x = [[0, 1], [5, 1], [15, 2], [25, 5], [35, 11], [45, 15], [55, 34], [60, 35]]
y = [4, 5, 20, 14, 32, 22, 38, 43]
x, y = np.array(x), np.array(y)

#You need to add the column of ones to the inputs if you want statsmodels to calculate the intercept 𝑏₀. It doesn’t takes 𝑏₀ into account by default. This is just one function call:
#
x = sm.add_constant(x)

print(x)
#[[ 1.  0.  1.]
# [ 1.  5.  1.]
# [ 1. 15.  2.]
# [ 1. 25.  5.]
# [ 1. 35. 11.]
# [ 1. 45. 15.]
# [ 1. 55. 34.]
# [ 1. 60. 35.]]

print(y)
#[ 4  5 20 14 32 22 38 43]


##Step 3: Create a model and fit it

#The regression model based on ordinary least squares is an instance of the class statsmodels.regression.linear_model.OLS. This is how you can obtain one:

model = sm.OLS(y, x)

results = model.fit()


##Step 4: Get results

print(results.summary())
#In this particular case, you might obtain the warning related to kurtosistest. This is due to the small number of observations provided.

#1. .rsquared holds 𝑅².
print('coefficient of determination:', results.rsquared)
#coefficient of determination: 0.8615939258756777
#2. .rsquared_adj represents adjusted 𝑅² (𝑅² corrected according to the number of input features).
print('adjusted coefficient of determination:', results.rsquared_adj)
#adjusted coefficient of determination: 0.8062314962259488
#3. params refers the array with 𝑏₀, 𝑏₁, and 𝑏₂ respectively.
print('regression coefficients:', results.params)
#regression coefficients: [5.52257928 0.44706965 0.25502548]


## Step 5: Predict response

print('predicted response:', results.fittedvalues, sep='\n')
#predicted response:
#[ 5.77760476  8.012953   12.73867497 17.9744479  23.97529728 29.4660957
# 38.78227633 41.27265006]
print('predicted response:', results.predict(x), sep='\n')
#predicted response:
#[ 5.77760476  8.012953   12.73867497 17.9744479  23.97529728 29.4660957
# 38.78227633 41.27265006]

x_new = sm.add_constant(np.arange(10).reshape((-1, 2)))
print(x_new)
#[[1. 0. 1.]
# [1. 2. 3.]
# [1. 4. 5.]
# [1. 6. 7.]
# [1. 8. 9.]]
y_new = results.predict(x_new)
print(y_new)
#[ 5.77760476  7.18179502  8.58598528  9.99017554 11.3943658 ]


#####Beyond Linear Regression

#Linear regression is sometimes not appropriate, especially for non-linear models of high complexity.

#Fortunately, there are other regression techniques suitable for the cases where linear regression doesn’t work well. Some of them are support vector machines, decision trees, random forest, and neural networks.



#####Conclusion






Figures
Figure_Simple_Linear_Regression_With_scikit-learn.png



Reference

Linear Regression in Python
by Mirko Stojiljkovic
https://realpython.com/linear-regression-in-python/

Deep Learning (Regression, Multiple Features/Explanatory Variables, Supervised Learning): Impelementation and Showing Biases and Weights

Deep Learning (Regression, Multiple Features/Explanatory Variables, Supervised Learning): Impelementation and Showing Biases and Weights ...