-
Notifications
You must be signed in to change notification settings - Fork 11
/
BaseGraphicalLasso.py
238 lines (219 loc) · 9.83 KB
/
BaseGraphicalLasso.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import numpy as np
import time
from DataHandler import DataHandler
class BaseGraphicalLasso(object):
# The parent class for Graphical Lasso
# problems. Most of the methods and
# attributes are defined and initialized here.
np.set_printoptions(precision=3)
""" Initialize attributes, read data """
def __init__(self, filename, blocks, lambd, beta,
processes, penalty_function="group_lasso",
datecolumn=True):
self.datecolumn = datecolumn
self.processes = processes
self.blocks = blocks
self.penalty_function = penalty_function
self.dimension = None
self.emp_cov_mat = [0] * self.blocks
self.real_thetas = [0] * self.blocks
if self.datecolumn:
self.blockdates = [0] * self.blocks
self.read_data(filename)
self.rho = self.get_rho()
self.max_step = 0.1
self.lambd = lambd
self.beta = beta
self.thetas = [np.ones((self.dimension, self.dimension))] * self.blocks
self.z0s = [np.ones((self.dimension, self.dimension))] * self.blocks
self.z1s = [np.ones((self.dimension, self.dimension))] * self.blocks
self.z2s = [np.ones((self.dimension, self.dimension))] * self.blocks
self.u0s = [np.zeros((self.dimension, self.dimension))] * self.blocks
self.u1s = [np.zeros((self.dimension, self.dimension))] * self.blocks
self.u2s = [np.zeros((self.dimension, self.dimension))] * self.blocks
self.eta = float(self.obs)/float(3*self.rho)
self.e = 1e-5
self.roundup = 1
""" Read data from the given file. Get parameters of data
(number of data samples, observations in a block).
Compute empirical covariance matrices.
Compute real inverse covariance matrices,
if provided in the second line of the data file. """
def read_data(self, filename, comment="#", splitter=","):
with open(filename, "r") as f:
comment_count = 0
for i, line in enumerate(f):
if comment in line:
comment_count += 1
else:
if self.dimension is None:
if self.datecolumn:
self.dimension = len(line.split(splitter)) - 1
else:
self.dimension = len(line.split(splitter))
self.datasamples = i + 1 - comment_count
self.obs = self.datasamples / self.blocks
with open(filename, "r") as f:
lst = []
block = 0
count = 0
for i, line in enumerate(f):
if comment in line:
if i == 1:
self.generate_real_thetas(line, splitter)
continue
if count == 0 and self.datecolumn is True:
start_date = line.strip().split(splitter)[0]
if self.datecolumn:
lst.append([float(x)
for x in np.array(line.strip().
split(splitter)[1:])])
else:
lst.append([float(x)
for x in np.array(line.strip().
split(splitter))])
count += 1
if count == self.obs:
if self.datecolumn:
end_date = line.strip().split(splitter)[0]
self.blockdates[block] = start_date + " - " + end_date
datablck = np.array(lst)
tp = datablck.transpose()
self.emp_cov_mat[block] = np.real(
np.dot(tp, datablck)/self.obs)
lst = []
count = 0
block += 1
""" Computes real inverse covariance matrices with DataHandler,
if provided in the second line of the data file """
def generate_real_thetas(self, line, splitter):
dh = DataHandler()
infos = line.split(splitter)
for network_info in infos:
filename = network_info.split(":")[0].strip("#").strip()
datacount = network_info.split(":")[1].strip()
sub_blocks = int(datacount)/self.obs
for i in range(sub_blocks):
dh.read_network(filename, inversion=False)
self.real_thetas = dh.inverse_sigmas
dh = None
""" Assigns rho based on number of observations in a block """
def get_rho(self):
return float(self.obs + 0.1) / float(3)
""" The core of the ADMM algorithm. To be called separately.
Contains calls to the three update methods, which are to be
defined in the child classes. """
def run_algorithm(self, max_iter=10000):
self.init_algorithm()
self.iteration = 0
stopping_criteria = False
thetas_pre = []
start_time = time.time()
while self.iteration < max_iter and stopping_criteria is False:
if self.iteration % 500 == 0 or self.iteration == 1:
print "\n*** Iteration %s ***" % self.iteration
print "Time passed: {0:.3g}s".format(time.time() - start_time)
print "Rho: %s" % self.rho
print "Eta: %s" % self.eta
print "Step: {0:.3f}".format(1/(2*self.eta))
if self.iteration % 500 == 0 or self.iteration == 1:
s_time = time.time()
self.theta_update()
if self.iteration % 500 == 0 or self.iteration == 1:
print "Theta update: {0:.3g}s".format(time.time() - s_time)
if self.iteration % 500 == 0 or self.iteration == 1:
s_time = time.time()
self.z_update()
if self.iteration % 500 == 0 or self.iteration == 1:
print "Z-update: {0:.3g}s".format(time.time() - s_time)
if self.iteration % 500 == 0 or self.iteration == 1:
s_time = time.time()
self.u_update()
if self.iteration % 500 == 0 or self.iteration == 1:
print "U-update: {0:.3g}s".format(time.time() - s_time)
""" Check stopping criteria """
if self.iteration % 500 == 0 or self.iteration == 1:
s_time = time.time()
if self.iteration > 0:
fro_norm = 0
for i in range(self.blocks):
dif = self.thetas[i] - thetas_pre[i]
fro_norm += np.linalg.norm(dif)
if fro_norm < self.e:
stopping_criteria = True
thetas_pre = list(self.thetas)
self.iteration += 1
self.run_time = "{0:.3g}".format(time.time() - start_time)
self.final_tuning(stopping_criteria, max_iter)
def theta_update(self):
pass
def z_update(self):
pass
def u_update(self):
pass
def terminate_processes(self):
pass
def init_algorithm(self):
pass
""" Performs final tuning for the converged thetas,
closes possible multiprocesses. """
def final_tuning(self, stopping_criteria, max_iter):
self.thetas = [np.round(theta, self.roundup) for theta in self.thetas]
self.only_true_false_edges()
self.terminate_processes()
if stopping_criteria:
print "\nIterations to complete: %s" % self.iteration
else:
print "\nMax iterations (%s) reached" % max_iter
""" Converts values in the thetas into boolean values,
informing only the existence of an edge without weight. """
def only_true_false_edges(self):
for k in range(self.blocks):
for i in range(self.dimension - 1):
for j in range(i + 1, self.dimension):
if self.thetas[k][i, j] != 0:
self.thetas[k][i, j] = 1
self.thetas[k][j, i] = 1
else:
self.thetas[k][i, j] = 0
self.thetas[k][j, i] = 0
""" Computes the Temporal Deviations between neighboring
thetas, both absolute and normalized values. """
def temporal_deviations(self):
self.deviations = np.zeros(self.blocks - 1)
for i in range(0, self.blocks - 1):
dif = self.thetas[i+1] - self.thetas[i]
np.fill_diagonal(dif, 0)
self.deviations[i] = np.linalg.norm(dif)
try:
self.norm_deviations = self.deviations/max(self.deviations)
self.dev_ratio = float(max(self.deviations))/float(
np.mean(self.deviations))
except ZeroDivisionError:
self.norm_deviations = self.deviations
self.dev_ratio = 0
""" Computes the measures of correct edges in thetas,
if true inverse covariance matrices are provided. """
def correct_edges(self):
self.real_edges = 0
self.real_edgeless = 0
self.correct_positives = 0
self.all_positives = 0
for real_network, network in zip(self.real_thetas, self.thetas):
for i in range(self.dimension - 1):
for j in range(i + 1, self.dimension):
if real_network[i, j] != 0:
self.real_edges += 1
if network[i, j] != 0:
self.correct_positives += 1
self.all_positives += 1
elif real_network[i, j] == 0:
self.real_edgeless += 1
if network[i, j] != 0:
self.all_positives += 1
self.precision = float(self.correct_positives)/float(
self.all_positives)
self.recall = float(self.correct_positives)/float(
self.real_edges)
self.f1score = 2*(self.precision*self.recall)/float(
self.precision + self.recall)