2010-10-26 04:37:57 +08:00
|
|
|
"""
|
|
|
|
|
==========================
|
|
|
|
|
SGD: Convex Loss Functions
|
|
|
|
|
==========================
|
|
|
|
|
|
2011-12-24 02:12:26 +08:00
|
|
|
Plot the convex loss functions supported by
|
|
|
|
|
`sklearn.linear_model.stochastic_gradient`.
|
2010-10-26 04:37:57 +08:00
|
|
|
"""
|
2010-11-01 23:46:40 +08:00
|
|
|
print __doc__
|
2010-10-26 04:37:57 +08:00
|
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
|
import pylab as pl
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn.linear_model.sgd_fast import Hinge, \
|
2010-11-30 19:14:30 +08:00
|
|
|
ModifiedHuber, SquaredLoss
|
2010-10-26 04:37:57 +08:00
|
|
|
|
2010-11-01 23:46:40 +08:00
|
|
|
###############################################################################
|
|
|
|
|
# Define loss funcitons
|
2010-10-26 04:37:57 +08:00
|
|
|
xmin, xmax = -3, 3
|
2012-02-02 05:52:37 +08:00
|
|
|
hinge = Hinge(1)
|
2010-10-26 04:37:57 +08:00
|
|
|
log_loss = lambda z, p: np.log2(1.0 + np.exp(-z))
|
|
|
|
|
modified_huber = ModifiedHuber()
|
2010-11-23 03:12:33 +08:00
|
|
|
squared_loss = SquaredLoss()
|
2010-11-01 23:46:40 +08:00
|
|
|
|
|
|
|
|
###############################################################################
|
|
|
|
|
# Plot loss funcitons
|
2010-10-26 04:37:57 +08:00
|
|
|
xx = np.linspace(xmin, xmax, 100)
|
2010-11-06 00:30:15 +08:00
|
|
|
pl.plot([xmin, 0, 0, xmax], [1, 1, 0, 0], 'k-',
|
|
|
|
|
label="Zero-one loss")
|
2011-12-24 02:12:26 +08:00
|
|
|
pl.plot(xx, [hinge.loss(x, 1) for x in xx], 'g-',
|
2010-11-06 00:30:15 +08:00
|
|
|
label="Hinge loss")
|
2011-12-24 02:12:26 +08:00
|
|
|
pl.plot(xx, [log_loss(x, 1) for x in xx], 'r-',
|
2010-11-06 00:30:15 +08:00
|
|
|
label="Log loss")
|
2011-12-24 02:12:26 +08:00
|
|
|
pl.plot(xx, [modified_huber.loss(x, 1) for x in xx], 'y-',
|
2010-11-06 00:30:15 +08:00
|
|
|
label="Modified huber loss")
|
2011-12-24 02:12:26 +08:00
|
|
|
#pl.plot(xx, [2.0*squared_loss.loss(x, 1) for x in xx], 'c-',
|
2010-11-23 03:12:33 +08:00
|
|
|
# label="Squared loss")
|
2010-10-26 04:37:57 +08:00
|
|
|
pl.ylim((0, 5))
|
|
|
|
|
pl.legend(loc="upper right")
|
2010-10-27 03:11:18 +08:00
|
|
|
pl.xlabel(r"$y \cdot f(x)$")
|
|
|
|
|
pl.ylabel("$L(y, f(x))$")
|
2010-10-26 04:37:57 +08:00
|
|
|
pl.show()
|