天天看点

python画指数函数图像_python中指数函数的回归线拟合

我正在学习如何解释用Python创建的指数函数的线性回归模型。我创建了一个模型,首先通过取自然对数将指数Y数据转换成直线。然后我创建一个线性模型,并记录坡度和截距。最后,我尝试使用斜率和截距来计算样本值。具体地说,当X=1.1时,我试图计算Y。Y应该是~2.14,但是我的模型解释得到的Y值是3.78。在

问题1:我在解释模型时做错了什么。在

问题2:我必须改变X数组的形状,否则在重新装配. 为什么我要改变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)