import numpy as np
from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
if __name__ == "__main__":
N = 50
np.random.seed(0)
x = np.sort(np.random.uniform(0, 6, N), axis=0)
y = 2 * np.cos(x) + 0.1 * np.random.randn(N)
x = x.reshape(-1, 1)
model = SVR(kernel='rbf')
c = np.logspace(-2, 2, 10)
gamma = np.logspace(-2, 2, 10)
svr = GridSearchCV(model, param_grid={'C': c, 'gamma': gamma}, cv=5)
svr.fit(x, y)
print('C和gamma的最优参数:\n', svr.best_params_)
x_test = np.linspace(x.min(), x.max(), 100).reshape(-1, 1)
y_predict = svr.predict(x_test)
sp = svr.best_estimator_.support_
plt.figure(facecolor='w')
plt.scatter(x[sp], y[sp], c='b', marker='o', label='Support Vectors')
plt.plot(x_test, y_predict, 'r--', label='RBF Kernel')
plt.plot(x, y, 'g-')
plt.legend(loc='best')
plt.title('SVR with grid_search C & gamma')
plt.xlabel('X')
plt.ylabel('Y')
plt.grid(True)
plt.tight_layout()
plt.show()
SVM successful one
于 2021-01-15 08:14:44 首次发布