简体   繁体   English

使回归线适合python中的指数函数

[英]Fit regression line to exponential function in python

I am trying to learn how to interpret a linear regression model for an exponential function created with Python. 我正在尝试学习如何为使用Python创建的指数函数解释线性回归模型。 I create a model by first transforming the exponential Y data into a straight line by taking the natural log. 我首先通过采用自然对数将指数Y数据转换为直线来创建模型。 I then create a linear model and note the slope and intercept. 然后,我创建一个线性模型并记下斜率和截距。 Lastly, I try to compute a sample value using the slope and intercept. 最后,我尝试使用斜率和截距来计算样本值。 Specifically, I try to compute the Y when X = 1.1. 具体来说,当X = 1.1时,我尝试计算Y。 Y should be ~2.14 but my model interpretation produces a Y value of 3.78. Y应该是〜2.14,但是我的模型解释得出的Y值为3.78。

Question 1: What am I doing wrong in interpreting the model. 问题1:我在解释模型时做错了什么。

Question 2: I have to reshape the X array or I get an error in regr.fit. 问题2:我必须重塑X数组的形状,否则regr.fit会出错。 Why do I have to reshape the X array. 为什么我必须重塑X数组。

The code follows: 代码如下:

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)

Make sure you've got the latest version of scikit; 确保您拥有最新版本的scikit; I got different coeffiecients to you: 我给你带来了不同的评价:

Slope:
 [ 0.69314718]
Intercept:
 4.4408920985e-16

And you'll need to take the exp of the whole expression, not just the x term: 而且,您需要获取整个表达式的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM