Fit regression line to exponential function in python
<p>I am trying to learn how to interpret a linear regression model for an exponential function created with Python.  I create a model by first transforming the exponential Y data into a straight line by taking the natural log.  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.  Y should be ~2.14 but my model interpretation produces a Y value of 3.78.  </p>

<p>Question 1: What am I doing wrong in interpreting the model.</p>

<p>Question 2: I have to reshape the X array or I get an error in regr.fit.  Why do I have to reshape the X array.</p>

<p>The code follows:</p>

<pre><code>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)
</code></pre>

<p>Make sure you've got the latest version of scikit; I got different coeffiecients to you: </p>

<pre><code>Slope:
 [ 0.69314718]
Intercept:
 4.4408920985e-16
</code></pre>

<p>And you'll need to take the <code>exp</code> of the whole expression, not just the x term:</p>

<pre><code>In [17]: np.exp(0.69314718*1.1 + 4.4408920985e-16)
Out[17]: 2.1435469237522917
</code></pre>

python python-3.x numpy machine-learning linear-regression