-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutils.py
136 lines (103 loc) · 2.6 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# -*- coding: utf-8 -*-
"""
Some utils for working on real vectors stored as dictionaries
Author: Stéphane Nicolet
"""
import random
import math
import array
### Helper functions
def norm2(m):
"""
Return the L2-norm of the point m
"""
s = 0.0
for (name, value) in m.items():
s += value ** 2
return math.sqrt(s)
def norm1(m):
"""
Return the L1-norm of the point m
"""
s = 0.0
for (name, value) in m.items():
s += abs(value)
return s
def linear_combinaison(alpha = 1.0, m1 = {},
beta = None, m2 = {}):
"""
Return the linear combinaison m = alpha * m1 + beta * m2.
"""
if m2 == {}:
m2 = m1
beta = 0.0
m = {}
for (name, value) in m1.items():
m[name] = alpha * value + beta * m2.get(name, 0.0)
return m
def difference(m1, m2):
"""
Return the difference m = m1 - m2.
"""
return linear_combinaison(1.0, m1, -1.0, m2)
def sum(m1, m2):
"""
Return the sum m = m1 + m2.
"""
return linear_combinaison(1.0, m1, 1.0, m2)
def hadamard_product(m1, m2):
"""
Return a vector where each entry is the product of the corresponding
entries in m1 and m2
"""
m = {}
for (name, value) in m1.items():
m[name] = value * m2.get(name, 0.0)
return m
def regulizer(m, lambd , alpha):
"""
Return a regulizer r = lamdb * ((1 - alpha) * norm1(m) + alpha * norm2(m))
Useful to transform non-convex optimization problems into pseudo-convex ones
"""
return lambd * ((1 - alpha) * norm1(m) + alpha * norm2(m))
def sign_of(x):
"""
The sign function for a real or integer parameter
Return -1, 0 or 1 depending of the sign of x
"""
return (x and (1, -1)[x < 0])
def sign(m):
"""
Return a vector filled by the signs of m, component by component
"""
result = {}
for (name, value) in m.items():
result[name] = sign_of(value)
return result
def sqrt(m):
"""
Return a vector filled by the square roots of m, component by component
"""
result = {}
for (name, value) in m.items():
result[name] = math.sqrt(value)
return result
def copy_and_fill(m, v):
"""
Return a vector with the same component as m, filled with v
"""
result = {}
for (name, foo) in m.items():
result[name] = v
return result
def pretty(m):
"""
Return a string representation of m
"""
s = "{ "
for name in sorted(m):
s += name + " ="
if m[name] >= 0: s += " "
s += str("%.4f" % m[name]) + "; "
s += "}"
return s