将回归线拟合到 python 中的指数函数
Fit regression line to exponential function in python
我正在尝试学习如何解释使用 Python 创建的指数函数的线性回归模型。我首先通过采用自然对数将指数 Y 数据转换为直线来创建模型。然后我创建一个线性模型并记下斜率和截距。最后,我尝试使用斜率和截距来计算样本值。具体来说,我尝试在 X = 1.1 时计算 Y。 Y 应该是 ~2.14,但我的模型解释产生了 3.78 的 Y 值。
问题 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
我正在尝试学习如何解释使用 Python 创建的指数函数的线性回归模型。我首先通过采用自然对数将指数 Y 数据转换为直线来创建模型。然后我创建一个线性模型并记下斜率和截距。最后,我尝试使用斜率和截距来计算样本值。具体来说,我尝试在 X = 1.1 时计算 Y。 Y 应该是 ~2.14,但我的模型解释产生了 3.78 的 Y 值。
问题 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