2010-09-01 01:39:48 +08:00
|
|
|
"""
|
2010-11-02 18:38:06 +08:00
|
|
|
===================================================================
|
|
|
|
|
Support Vector Regression (SVR) using linear and non-linear kernels
|
|
|
|
|
===================================================================
|
|
|
|
|
|
2013-09-28 23:38:02 +08:00
|
|
|
Toy example of 1D regression using linear, polynomial and RBF kernels.
|
2010-11-02 18:38:06 +08:00
|
|
|
|
2010-08-13 17:52:50 +08:00
|
|
|
"""
|
2013-02-01 22:04:03 +08:00
|
|
|
print(__doc__)
|
2010-11-02 18:38:06 +08:00
|
|
|
|
2010-08-13 17:53:43 +08:00
|
|
|
import numpy as np
|
2014-03-05 16:55:33 +08:00
|
|
|
from sklearn.svm import SVR
|
2014-05-15 04:31:03 +08:00
|
|
|
import matplotlib.pyplot as plt
|
2010-08-13 17:53:43 +08:00
|
|
|
|
2014-03-05 16:55:33 +08:00
|
|
|
###############################################################################
|
|
|
|
|
# Generate sample data
|
2011-12-17 05:55:42 +08:00
|
|
|
X = np.sort(5 * np.random.rand(40, 1), axis=0)
|
2010-08-13 17:52:50 +08:00
|
|
|
y = np.sin(X).ravel()
|
|
|
|
|
|
|
|
|
|
###############################################################################
|
2010-08-13 17:53:43 +08:00
|
|
|
# Add noise to targets
|
2011-12-17 05:55:42 +08:00
|
|
|
y[::5] += 3 * (0.5 - np.random.rand(8))
|
2010-08-13 17:52:50 +08:00
|
|
|
|
|
|
|
|
###############################################################################
|
|
|
|
|
# Fit regression model
|
2012-05-05 20:56:19 +08:00
|
|
|
svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)
|
|
|
|
|
svr_lin = SVR(kernel='linear', C=1e3)
|
|
|
|
|
svr_poly = SVR(kernel='poly', C=1e3, degree=2)
|
2010-08-13 17:52:50 +08:00
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
###############################################################################
|
|
|
|
|
# look at the results
|
2015-10-22 19:59:52 +08:00
|
|
|
lw = 2
|
|
|
|
|
plt.scatter(X, y, color='darkorange', label='data')
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.hold('on')
|
2015-10-22 19:59:52 +08:00
|
|
|
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')
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.xlabel('data')
|
|
|
|
|
plt.ylabel('target')
|
|
|
|
|
plt.title('Support Vector Regression')
|
|
|
|
|
plt.legend()
|
|
|
|
|
plt.show()
|