scikit-learn/examples/svm/plot_weighted_samples.py

64 lines
1.9 KiB
Python
Raw Normal View History

"""
=====================
SVM: Weighted samples
=====================
Plot decision function of a weighted dataset, where the size of points
is proportional to its weight.
2013-07-26 16:50:06 +08:00
The sample weighting rescales the C parameter, which means that the classifier
puts more emphasis on getting these points right. The effect might often be
subtle.
To emphasis the effect here, we particularly weight outliers, making the
deformation of the decision boundary very visible.
"""
print(__doc__)
import numpy as np
2013-07-26 16:50:06 +08:00
import matplotlib.pyplot as plt
from sklearn import svm
2013-07-26 16:50:06 +08:00
def plot_decision_function(classifier, sample_weight, axis, title):
# plot the decision function
xx, yy = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500))
Z = classifier.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# plot the line, the points, and the nearest vectors to the plane
axis.contourf(xx, yy, Z, alpha=0.75, cmap=plt.cm.bone)
axis.scatter(X[:, 0], X[:, 1], c=Y, s=100 * sample_weight, alpha=0.9,
cmap=plt.cm.bone)
axis.axis('off')
axis.set_title(title)
# we create 20 points
np.random.seed(0)
2010-11-28 07:21:05 +08:00
X = np.r_[np.random.randn(10, 2) + [1, 1], np.random.randn(10, 2)]
2011-12-17 05:55:42 +08:00
Y = [1] * 10 + [-1] * 10
2013-07-26 16:50:06 +08:00
sample_weight_last_ten = abs(np.random.randn(len(X)))
sample_weight_constant = np.ones(len(X))
# and bigger weights to some outliers
2013-07-26 16:50:06 +08:00
sample_weight_last_ten[15:] *= 5
sample_weight_last_ten[9] *= 15
2013-07-26 16:50:06 +08:00
# for reference, first fit without class weights
2013-07-26 16:50:06 +08:00
# fit the model
clf_weights = svm.SVC()
clf_weights.fit(X, Y, sample_weight=sample_weight_last_ten)
2013-07-26 16:50:06 +08:00
clf_no_weights = svm.SVC()
clf_no_weights.fit(X, Y)
2013-07-26 16:50:06 +08:00
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
plot_decision_function(clf_no_weights, sample_weight_constant, axes[0],
"Constant weights")
plot_decision_function(clf_weights, sample_weight_last_ten, axes[1],
"Modified weights")
2013-07-26 16:50:06 +08:00
plt.show()