Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

python - Can I use numpy.polyfit(x, y, deg) for multiple linear regression

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.

question from:https://stackoverflow.com/questions/65949580/can-i-use-numpy-polyfitx-y-deg-for-multiple-linear-regression

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming your equation is a * exercise + b * age + intercept = y, you can fit a multiple linear regression with numpy or scikit-learn as follows:

from sklearn import linear_model
import numpy as np
np.random.seed(42)

X = np.random.randint(low=1, high=10, size=20).reshape(10, 2)
X = np.c_[X, np.ones(X.shape[0])]  # add intercept
y = np.random.randint(low=1, high=10, size=10)

# Option 1
a, b, intercept = np.linalg.pinv((X.T).dot(X)).dot(X.T.dot(y))
print(a, b, intercept)

# Option 2
a, b, intercept = np.linalg.lstsq(X,y, rcond=None)[0]
print(a, b, intercept)

# Option 3
clf = linear_model.LinearRegression(fit_intercept=False)
clf.fit(X, y)
print(clf.coef_)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...