[英]Fit regression line to exponential function in python
我正在尝试学习如何为使用Python创建的指数函数解释线性回归模型。 我首先通过采用自然对数将指数Y数据转换为直线来创建模型。 然后,我创建一个线性模型并记下斜率和截距。 最后,我尝试使用斜率和截距来计算样本值。 具体来说,当X = 1.1时,我尝试计算Y。 Y应该是〜2.14,但是我的模型解释得出的Y值为3.78。
问题1:我在解释模型时做错了什么。
问题2:我必须重塑X数组的形状,否则regr.fit会出错。 为什么我必须重塑X数组。
代码如下:
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
# create some exponential data
X = np.arange(1, 10, 0.1)
print(X)
Y = np.power(2, X)
print(Y)
# transform the exponential Y data to make it a straight line
ln_Y = np.log(Y)
# show the exponential plot
plt.scatter(X, Y)
plt.show()
# Create linear regression object
regr = linear_model.LinearRegression()
# reshape the X to avoid regr.fit errors
X = np.reshape(X, (X.size, 1))
# Train the model using the training sets
regr.fit(X,ln_Y)
# The coefficients
print('Slope: \n', regr.coef_)
print('Intercept: \n', regr.intercept_)
# predict Y when X = 1.1 (should be approximately 2.14354693)
# equation = e^(0.00632309*1.1) + 2.7772517886
print("predicted val = ", np.exp(0.00632309*1.1) + 2.7772517886)
确保您拥有最新版本的scikit; 我给你带来了不同的评价:
Slope:
[ 0.69314718]
Intercept:
4.4408920985e-16
而且,您需要获取整个表达式的exp
,而不仅仅是x项:
In [17]: np.exp(0.69314718*1.1 + 4.4408920985e-16)
Out[17]: 2.1435469237522917
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.