简体   繁体   English

使用sklearn,numpy和matplotlib在Python中进行多项式回归

[英]Polynomial regression in Python using sklearn, numpy and matplotlib

I'm trying to make a small program that will plot a graph with best fit line and that will predict the COST value based on inputted SIZE value. 我正在尝试制作一个小程序,该程序将绘制具有最佳拟合线的图形,并根据输入的SIZE值预测COST值。

I always get this error, and I do not know what it means: 我总是会收到此错误,并且我不知道这意味着什么:

DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
No handles with labels found to put in legend.

This is the graph that I get (red), and I think that curve should look like green curve that i have draw. 这是我得到的图形(红色),我认为曲线应该看起来像我绘制的绿色曲线。

在此处输入图片说明

And finally, program makes prediction only when I exit the graph. 最后,只有当我退出图形时,程序才会做出预测。 What am I doing wrong? 我究竟做错了什么? This is the code: 这是代码:

import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt

size=[[1],[2],[3],[4],[5],[7],[9],[10],[11],[13]]
cost=[[10],[22],[35],[48],[60],[80],[92],[111],[118],[133]]

def predict(size,cost,x):

    dates=np.reshape(size,(len(size),1))

    svr_poly=SVR(kernel="poly",C=1e3, degree=2)
    svr_poly.fit(size,cost)

    plt.scatter(size,cost, color="blue")
    plt.plot(cost, svr_poly.predict(cost), color="red")

    plt.xlabel("Size")
    plt.ylabel("Cost")
    plt.title("prediction")
    plt.legend()

    plt.show()

predictedcost=predict(size,cost,7)

print(predictedcost)

Here, I found the answer to this problem. 在这里,我找到了这个问题的答案。 So if you are interested, check it 因此,如果您有兴趣,请检查一下

import numpy as np
import matplotlib.pyplot as plt
import math

X = np.array([1,2,3,5,6,7,4,7,8,9,5,10,11,7,6,6,10,11,11,12,13,13,14])
Y=np.array([2,3,5,8,11,14,9,19,15,19,15,16,14,7,13,13,14,13,23,25,26,27,33])

koeficienti_polinom = np.polyfit(X, Y, 2)

a=koeficienti_polinom[0]
b=koeficienti_polinom[1]
c=koeficienti_polinom[2]

xval=np.linspace(np.min(X), np.max(X))   

regression=a * xval**2 + b*xval + c 

predX = float(input("Enter: "))      
predY = a * predX**2 + b*predX + c   

plt.scatter(X,Y, s=20, color="blue" )      
plt.scatter(predX, predY, color="red")    
plt.plot(xval, regression, color="black", linewidth=1)      

print("Kvadratno predvidjanje: ",round(predY,2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM