Tuesday, April 7, 2020

polynomial regression in machine learning using python

from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(2)
page_speeds = np.random.normal(3.0,1.0,100)
purchase_amount = np.random.normal(50.0,30.0,100)/page_speeds

plt.scatter(page_speeds,purchase_amount)
Out[3]:
<matplotlib.collections.PathCollection at 0x27ca0f7e788>
In [4]:
train_x = page_speeds[:80]
test_x = page_speeds[80:]

train_y = purchase_amount[:80]
test_y = purchase_amount[80:]
In [5]:
plt.scatter(train_x,train_y)
Out[5]:
<matplotlib.collections.PathCollection at 0x27ca0fee248>
In [7]:
plt.scatter(test_x,test_y)
Out[7]:
<matplotlib.collections.PathCollection at 0x27ca10fcb48>
In [10]:
x =np.array(train_x)
y =np.array(train_y)

p4 = np.poly1d(np.polyfit(x,y,8))
In [12]:
import matplotlib.pyplot as plt

xp =np.linspace(0,7,100)
axes = plt.axes()
axes.set_xlim([0,7])
axes.set_ylim([0,200])
plt.scatter(x,y)
plt.plot(xp,p4(xp),c='r')
plt.show()
In [13]:
testx =np.array(test_x)
testy =np.array(test_y)


axes = plt.axes()
axes.set_xlim([0,7])
axes.set_ylim([0,200])
plt.scatter(testx,testy)
plt.plot(xp,p4(xp),c='r')
plt.show()
In [14]:
from sklearn.metrics import r2_score
r2 =r2_score(testy,p4(testx))
print(r2)
0.30018168611266705
In [ ]:
 

python class topic video