<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Polynomial Regression
What if your data doesn't look linear at all? Let's look at some more realistic-looking page speed / purchase data
Step1:  numpy has a handy polyfit function we can use, to let us construct an nth-degree polynomial model of our data that minimizes squared error. Let's try it with a 4th degree polynomial
Step2:  We'll visualize our original scatter plot, together with a plot of our predicted values using the polynomial for page speed times ranging from 0-7 seconds
Step3:  Looks pretty good! Let's measure the r-squared error
<ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from pylab import *
np.random.seed(2)
pageSpeeds = np.random.normal(3.0, 1.0, 1000)
purchaseAmount = np.random.normal(50.0, 10.0, 1000) / pageSpeeds
scatter(pageSpeeds, purchaseAmount)
Explanation: Polynomial Regression
What if your data doesn't look linear at all? Let's look at some more realistic-looking page speed / purchase data:
End of explanation
x = np.array(pageSpeeds)
y = np.array(purchaseAmount)
p4 = np.poly1d(np.polyfit(x, y, 4))
Explanation: numpy has a handy polyfit function we can use, to let us construct an nth-degree polynomial model of our data that minimizes squared error. Let's try it with a 4th degree polynomial:
End of explanation
import matplotlib.pyplot as plt
xp = np.linspace(0, 7, 100)
plt.scatter(x, y)
plt.plot(xp, p4(xp), c='r')
plt.show()
Explanation: We'll visualize our original scatter plot, together with a plot of our predicted values using the polynomial for page speed times ranging from 0-7 seconds:
End of explanation
from sklearn.metrics import r2_score
r2 = r2_score(y, p4(x))
print r2
Explanation: Looks pretty good! Let's measure the r-squared error:
End of explanation
<END_TASK>