scikit-learn/examples/svm/plot_svm_regression.py

46 lines
1.4 KiB
Python
Raw Normal View History

"""
===================================================================
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-08-13 17:52:50 +08:00
"""
print(__doc__)
2010-08-13 17:52:50 +08:00
###############################################################################
# Generate sample data
2010-08-13 17:53:43 +08:00
import numpy as np
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
from sklearn.svm import SVR
2010-08-13 17:53:43 +08:00
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
2010-08-13 23:28:25 +08:00
import pylab as pl
2010-08-13 17:52:50 +08:00
pl.scatter(X, y, c='k', label='data')
pl.hold('on')
pl.plot(X, y_rbf, c='g', label='RBF model')
pl.plot(X, y_lin, c='r', label='Linear model')
pl.plot(X, y_poly, c='b', label='Polynomial model')
pl.xlabel('data')
pl.ylabel('target')
pl.title('Support Vector Regression')
pl.legend()
pl.show()