2011-03-16 02:58:56 +08:00
|
|
|
"""
|
|
|
|
|
=====================
|
2011-03-16 03:50:44 +08:00
|
|
|
SGD: Weighted samples
|
2011-03-16 02:58:56 +08:00
|
|
|
=====================
|
|
|
|
|
|
|
|
|
|
Plot decision function of a weighted dataset, where the size of points
|
|
|
|
|
is proportional to its weight.
|
|
|
|
|
"""
|
2013-02-01 22:04:03 +08:00
|
|
|
print(__doc__)
|
2011-03-16 02:58:56 +08:00
|
|
|
|
|
|
|
|
import numpy as np
|
2014-05-15 04:31:03 +08:00
|
|
|
import matplotlib.pyplot as plt
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn import linear_model
|
2011-03-16 02:58:56 +08:00
|
|
|
|
|
|
|
|
# we create 20 points
|
|
|
|
|
np.random.seed(0)
|
|
|
|
|
X = np.r_[np.random.randn(10, 2) + [1, 1], np.random.randn(10, 2)]
|
2011-12-24 02:12:26 +08:00
|
|
|
y = [1] * 10 + [-1] * 10
|
2011-03-16 02:58:56 +08:00
|
|
|
sample_weight = 100 * np.abs(np.random.randn(20))
|
|
|
|
|
# and assign a bigger weight to the last 10 samples
|
|
|
|
|
sample_weight[:10] *= 10
|
|
|
|
|
|
|
|
|
|
# plot the weighted data points
|
|
|
|
|
xx, yy = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500))
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.figure()
|
|
|
|
|
plt.scatter(X[:, 0], X[:, 1], c=y, s=sample_weight, alpha=0.9,
|
2017-06-07 19:23:12 +08:00
|
|
|
cmap=plt.cm.bone, edgecolor='black')
|
2011-03-16 02:58:56 +08:00
|
|
|
|
2017-06-07 19:23:12 +08:00
|
|
|
# fit the unweighted model
|
2019-01-17 18:41:13 +08:00
|
|
|
clf = linear_model.SGDClassifier(alpha=0.01, max_iter=100, tol=1e-3)
|
2011-03-16 02:58:56 +08:00
|
|
|
clf.fit(X, y)
|
|
|
|
|
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
|
|
|
|
|
Z = Z.reshape(xx.shape)
|
2014-05-15 04:31:03 +08:00
|
|
|
no_weights = plt.contour(xx, yy, Z, levels=[0], linestyles=['solid'])
|
2011-03-16 02:58:56 +08:00
|
|
|
|
2017-06-07 19:23:12 +08:00
|
|
|
# fit the weighted model
|
2019-01-17 18:41:13 +08:00
|
|
|
clf = linear_model.SGDClassifier(alpha=0.01, max_iter=100, tol=1e-3)
|
2011-03-16 02:58:56 +08:00
|
|
|
clf.fit(X, y, sample_weight=sample_weight)
|
|
|
|
|
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
|
|
|
|
|
Z = Z.reshape(xx.shape)
|
2014-05-15 04:31:03 +08:00
|
|
|
samples_weights = plt.contour(xx, yy, Z, levels=[0], linestyles=['dashed'])
|
2011-03-16 02:58:56 +08:00
|
|
|
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.legend([no_weights.collections[0], samples_weights.collections[0]],
|
2014-05-15 10:35:13 +08:00
|
|
|
["no weights", "with weights"], loc="lower left")
|
2011-03-16 02:58:56 +08:00
|
|
|
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.xticks(())
|
|
|
|
|
plt.yticks(())
|
|
|
|
|
plt.show()
|