how to draw polynomial regression graph in python?

Viewed 240

When I use the code below everything works fine and I get a beautiful graph.

# Model
f = np.polyfit(df[feature], y, order)
p = np.poly1d(f)
print(p) 

# Visualisation
def PlotPolly(model, independent_variable, dependent_variable, Name):
    x_new = np.linspace(df[feature].min(), df[feature].max(), 100)
    y_new = model(x_new)

    plt.plot(independent_variable, dependent_variable, '.', x_new, y_new, '-')
    plt.title('Polynomial Fit')
    ax = plt.gca()
    ax.set_facecolor((0.898, 0.898, 0.898))
    fig = plt.gcf()
    plt.xlabel(Name)
    plt.ylabel(target)

   plt.show()
   plt.close()

PlotPolly(p, X, y, feature) 

But when I define the model using sklearn I don't seem to be able to draw a graph

# Model
from sklearn.preprocessing import PolynomialFeatures
f = PolynomialFeatures(degree = 4)
p = f.fit_transform(X)
m = LinearRegression()
m.fit(p, y)

Model defined like that seems to work. but the code below only draws the red points correctly. The blue line is all over the place. What do I need to change in the code below for it to work? In case this information is needed my variables are defined in format:
X = df[[feature]]
y = df[target]

plt.scatter(X, y, color = 'red')
plt.plot(X, m.predict(f.fit_transform(X)), color = 'blue')
plt.title('Truth or Bluff (Polynomial Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
0 Answers
Related