Linear regression examples

In [1]:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
In [2]:
plt.rcParams['figure.figsize'] = (10, 10)

Linear

In [3]:
x = np.arange(-1.0, 10.1, 1.0)
y = 3.0 * x + 2.0
noise = np.random.normal(0.0, 2, x.shape[0])
yhat = y + noise
yhat = yhat.round(1)
In [4]:
plt.plot(x, yhat, 'k.')
Out[4]:
[<matplotlib.lines.Line2D at 0x2048eb90148>]
In [5]:
data = pd.DataFrame(np.array([x,yhat]).T, columns=['x', 'y'])
data
Out[5]:
x y
0 -1.0 -0.6
1 0.0 1.7
2 1.0 3.8
3 2.0 7.6
4 3.0 12.5
5 4.0 14.5
6 5.0 18.4
7 6.0 19.1
8 7.0 26.5
9 8.0 26.7
10 9.0 32.3
11 10.0 28.7

Quadratic

In [6]:
x = np.arange(-1.0, 10.1, 1.0)
y = x**2 - 8.0 * x + 16.0
noise = np.random.normal(0.0, 0.5, x.shape[0])
yhat = y + noise
yhat = yhat.round(1)
In [7]:
plt.plot(x, yhat, 'k.')
Out[7]:
[<matplotlib.lines.Line2D at 0x2048ebe91c8>]
In [8]:
data = pd.DataFrame(np.array([x,yhat]).T, columns=['x', 'y'])
data
Out[8]:
x y
0 -1.0 24.5
1 0.0 16.5
2 1.0 8.2
3 2.0 4.2
4 3.0 0.6
5 4.0 -0.7
6 5.0 1.4
7 6.0 4.1
8 7.0 8.9
9 8.0 15.5
10 9.0 25.2
11 10.0 36.1

Logistic

In [14]:
x = np.arange(-1.0, 10.1, 1.0)
y = 10.0 / (1.0 + np.exp(-(x - 5.0)))
noise = np.random.normal(0.0, .8, x.shape[0])
yhat = y + noise
yhat = yhat.round(1)
In [15]:
plt.plot(x, yhat, 'k.')
Out[15]:
[<matplotlib.lines.Line2D at 0x2048f1b6d08>]
In [11]:
data = pd.DataFrame(np.array([x,yhat]).T, columns=['x', 'y'])
data
Out[11]:
x y
0 -1.0 0.4
1 0.0 5.5
2 1.0 -3.2
3 2.0 1.6
4 3.0 0.7
5 4.0 1.7
6 5.0 5.7
7 6.0 8.7
8 7.0 8.0
9 8.0 8.0
10 9.0 6.8
11 10.0 13.3

End