我在 Ubuntu 18.04 LTS 中使用 Python 2.7.15rc1。我试图绘制支持向量回归图,但我没有得到任何输出。
import matplotlib
matplotlib.use("Agg")
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt
#Generate Sample data
x = np.sort(5 * np.random.rand(40, 1), axis = 0)
y = np.sin(x).ravel()
#Add noise to targets
y[::5] += 3 * (0.5 - np.random.rand(8))
#create classifier regression model
svr_rbf = SVR(kernel="rbf", C=1000, gamma=0.1)
svr_lin = SVR(kernel="linear", C=1000, gamma=0.1)
svr_poly = SVR(kernel="poly", C=1000, gamma=0.1)
#Fit regression model
y_rbf = svr_rbf.fit(x,y).predict(x)
y_lin = svr_lin.fit(x,y).predict(x)
y_poly = svr_poly.fit(x,y).predict(x)
#Plotting of results
lw = 2
plt.scatter(x, y, color="darkorange", label="data")
plt.plot(x, y_rbf, color="navy", lw=lw, label="RBF Model")
plt.plot(x, y_lin, color="c", lw=lw, label="Linear Model")
plt.plot(x, y_poly, color="cornflowerblue", lw=lw, label="Polynomial Model")
plt.xlabel("data")
plt.ylabel("target")
plt.title("Support Vector Regression")
plt.legend()
plt.show()
python svm.py 不输出任何内容。 我错过了要导入的东西吗?或者我们不能绘制这个图表? 我是机器学习新手
最佳答案
如果您在 Jupyter Ipython 笔记本上运行,则只需在代码顶部添加 %matplotlib inline
即可。您可以阅读更多相关信息here和 here .
否则,我复制了您的代码并删除了 matplotlib.use("Agg")
,它适用于 Ubuntu 18.04、matplotlib 版本 2.2.2。您能指定您使用的是哪个版本吗?
这也是代码,
import matplotlib
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt
#Generate Sample data
x = np.sort(5 * np.random.rand(40, 1), axis = 0)
y = np.sin(x).ravel()
#Add noise to targets
y[::5] += 3 * (0.5 - np.random.rand(8))
#create classifier regression model
svr_rbf = SVR(kernel="rbf", C=1000, gamma=0.1)
svr_lin = SVR(kernel="linear", C=1000, gamma=0.1)
svr_poly = SVR(kernel="poly", C=1000, gamma=0.1)
#Fit regression model
y_rbf = svr_rbf.fit(x,y).predict(x)
y_lin = svr_lin.fit(x,y).predict(x)
y_poly = svr_poly.fit(x,y).predict(x)
#Plotting of results
lw = 2
plt.scatter(x, y, color="darkorange", label="data")
plt.plot(x, y_rbf, color="navy", lw=lw, label="RBF Model")
plt.plot(x, y_lin, color="c", lw=lw, label="Linear Model")
plt.plot(x, y_poly, color="cornflowerblue", lw=lw, label="Polynomial Model")
plt.xlabel("data")
plt.ylabel("target")
plt.title("Support Vector Regression")
plt.legend()
plt.show()
关于python - 支持向量回归 (SVR) 在 Ubuntu 18.04 LTS 中未绘制任何图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50886428/