Skip to content
This repository has been archived by the owner on Dec 6, 2023. It is now read-only.

Commit

Permalink
Fix project_simplex.
Browse files Browse the repository at this point in the history
When the constraint is already satisfied, there is nothing to do.
  • Loading branch information
mblondel committed Jan 18, 2017
1 parent 4f84a18 commit dfb8586
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
3 changes: 3 additions & 0 deletions lightning/impl/penalty.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ def regularization(self, coef):
# See https://gist.github.com/mblondel/6f3b7aaad90606b98f71
# for more algorithms.
def project_simplex(v, z=1):
if np.sum(v) <= z:
return v

n_features = v.shape[0]
u = np.sort(v)[::-1]
cssv = np.cumsum(u) - z
Expand Down
42 changes: 40 additions & 2 deletions lightning/impl/tests/test_penalty.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,45 @@
import numpy as np
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_almost_equal, assert_array_almost_equal

from lightning.impl.penalty import project_l1_ball
from lightning.impl.penalty import project_l1_ball, project_simplex


def project_simplex_bisection(v, z=1, tau=0.0001, max_iter=1000):
lower = 0
upper = np.max(v)
current = np.inf

for it in xrange(max_iter):
if np.abs(current) / z < tau and current < 0:
break

theta = (upper + lower) / 2.0
w = np.maximum(v - theta, 0)
current = np.sum(w) - z
if current <= 0:
upper = theta
else:
lower = theta
return w


def test_proj_simplex():
rng = np.random.RandomState(0)

v = rng.rand(100)
w = project_simplex(v, z=10)
w2 = project_simplex_bisection(v, z=10, max_iter=100)
assert_array_almost_equal(w, w2, 3)

v = rng.rand(3)
w = project_simplex(v, z=1)
w2 = project_simplex_bisection(v, z=1, max_iter=100)
assert_array_almost_equal(w, w2, 3)

v = rng.rand(2)
w = project_simplex(v, z=1)
w2 = project_simplex_bisection(v, z=1, max_iter=100)
assert_array_almost_equal(w, w2, 3)


def test_proj_l1_ball():
Expand Down

0 comments on commit dfb8586

Please sign in to comment.