Python 通过最小二乘回归拟合多项式模型后,预测值的numpy等价物是什么?
假设我想通过最小二乘回归拟合度Python 通过最小二乘回归拟合多项式模型后,预测值的numpy等价物是什么?,python,numpy,scikit-learn,linear-regression,Python,Numpy,Scikit Learn,Linear Regression,假设我想通过最小二乘回归拟合度d的多项式模型。我在python中学习了两种方法。一个使用numpy,另一个使用sklearn。在我拟合模型并获得系数后,为了预测测试数据的值,在sklearn中,我可以执行以下操作: from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(x_train, y_train) # Fitting on Training Data model.pre
d
的多项式模型。我在python中学习了两种方法。一个使用numpy
,另一个使用sklearn
。在我拟合模型并获得系数后,为了预测测试数据的值,在sklearn
中,我可以执行以下操作:
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(x_train, y_train) # Fitting on Training Data
model.predict(20) #One value in test data is 20
使用以下方法拟合模型后,model.predict()
的numpy
等效值是什么:
import numpy.polynomial.polynomial as poly
np_model = poly.polyfit(x_train, y_train, d)
我使用numpy.polyval,文档位于-这里是一个使用polyval的图形多项式拟合器示例
我使用numpy.polyval,文档位于-这里是一个使用polyval的图形多项式拟合器示例
顺便说一下,将多项式顺序(代码顶部)设置为7以查看过拟合的丑陋示例。顺便说一下,将多项式顺序(代码顶部)设置为7以查看过拟合的丑陋示例。
import numpy, matplotlib
import matplotlib.pyplot as plt
xData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.0, 6.6, 7.7, 0.0])
yData = numpy.array([1.1, 20.2, 30.3, 40.4, 50.0, 60.6, 70.7, 0.1])
polynomialOrder = 2 # example quadratic
# curve fit the test data
fittedParameters = numpy.polyfit(xData, yData, polynomialOrder)
print('Fitted Parameters:', fittedParameters)
modelPredictions = numpy.polyval(fittedParameters, xData)
absError = modelPredictions - yData
SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))
print('RMSE:', RMSE)
print('R-squared:', Rsquared)
print()
##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
axes = f.add_subplot(111)
# first the raw data as a scatter plot
axes.plot(xData, yData, 'D')
# create data for the fitted equation plot
xModel = numpy.linspace(min(xData), max(xData))
yModel = numpy.polyval(fittedParameters, xModel)
# now the model as a line plot
axes.plot(xModel, yModel)
axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label
plt.show()
plt.close('all') # clean up after using pyplot
graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)