Is there any way I can fit two independent variables and one dependent variable in numpy.polyfit()?
I have a panda data frame that I loaded from a csv file. I wish to include two columns as independent variables to run multiple linear regression using NumPy.
Currently my simple linear regression looks like this:
model_combined = np.polyfit(data.Exercise, y, 1)
I wish to include data.Age
in x as well.
Advertisement
Answer
Assuming your equation is a * exercise + b * age + intercept = y
, you can fit a multiple linear regression with numpy or scikit-learn as follows:
JavaScript
x
21
21
1
from sklearn import linear_model
2
import numpy as np
3
np.random.seed(42)
4
5
X = np.random.randint(low=1, high=10, size=20).reshape(10, 2)
6
X = np.c_[X, np.ones(X.shape[0])] # add intercept
7
y = np.random.randint(low=1, high=10, size=10)
8
9
# Option 1
10
a, b, intercept = np.linalg.pinv((X.T).dot(X)).dot(X.T.dot(y))
11
print(a, b, intercept)
12
13
# Option 2
14
a, b, intercept = np.linalg.lstsq(X,y, rcond=None)[0]
15
print(a, b, intercept)
16
17
# Option 3
18
clf = linear_model.LinearRegression(fit_intercept=False)
19
clf.fit(X, y)
20
print(clf.coef_)
21