8000 Fix project_simplex. · scikit-learn-contrib/lightning@dfb8586 · GitHub
[go: up one dir, main page]

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

Commit dfb8586

Browse files
committed
Fix project_simplex.
When the constraint is already satisfied, there is nothing to do.
1 parent 4f84a18 commit dfb8586

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

lightning/impl/penalty.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@ def regularization(self, coef):
5353
# See https://gist.github.com/mblondel/6f3b7aaad90606b98f71
5454
# for more algorithms.
5555
def project_simplex(v, z=1):
56+
if np.sum(v) <= z:
57+
return v
58+
5659
n_features = v.shape[0]
5760
u = np.sort(v)[::-1]
5861
cssv = np.cumsum(u) - z

lightning/impl/tests/test_penalty.py

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,45 @@
11
import numpy as np
2-
from sklearn.utils.testing import assert_almost_equal
2+
from sklearn.utils.testing import assert_almost_equal, assert_array_almost_equal
33

4-
from lightning.impl.penalty import project_l1_ball
4+
from lightning.impl.penalty import project_l1_ball, project_simplex
5+
6+
7+
def project_simplex_bisection(v, z=1, tau=0.0001, max_iter=1000):
8+
lower = 0
9+
upper = np.max(v)
10+
current = np.inf
11+
12+
for it in xrange(max_iter):
13+
if np.abs(current) / z < tau and current < 0:
14+
break
15+
16+
theta = (upper + lower) / 2.0
17+
w = np.maximum(v - theta, 0)
18+
current = np.sum(w) - z
19+
if current <= 0:
20+
upper = theta
21+
else:
22+
lower = theta
23+
return w
24+
25+
26+
def test_proj_simplex():
27+
rng = np.random.RandomState(0)
28+
29+
v = rng.rand(100)
30+
w = project_simplex(v, z=10)
31+
w2 = project_simplex_bisection(v, z=10, max_iter=100)
32+
assert_array_almost_equal(w, w2, 3)
33+
34+
v = rng.rand(3)
35+
w = project_simplex(v, z=1)
36+
w2 = project_simplex_bisection(v, z=1, max_iter=100)
37+
assert_array_almost_equal(w, w2, 3)
38+
39+
v = rng.rand(2)
40+
w = project_simplex(v, z=1)
41+
w2 = project_simplex_bisection(v, z=1, max_iter=100)
42+
assert_array_almost_equal(w, w2, 3)
543

644

745
def test_proj_l1_ball():

0 commit comments

Comments
 (0)
0