-
Notifications
You must be signed in to change notification settings - Fork 7
/
synthetic_dataset.py
210 lines (174 loc) · 7.38 KB
/
synthetic_dataset.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
import logging
import igraph as ig
import networkx as nx
import numpy as np
from utils.utils import is_dag
class SyntheticDataset:
"""Generate synthetic data.
Key instance variables:
X (numpy.ndarray): [n, d] data matrix.
B (numpy.ndarray): [d, d] weighted adjacency matrix of DAG.
B_bin (numpy.ndarray): [d, d] binary adjacency matrix of DAG.
Code modified from:
https://github.com/xunzheng/notears/blob/master/notears/utils.py
"""
_logger = logging.getLogger(__name__)
def __init__(self, n, d, graph_type, degree, noise_type, B_scale, seed=1):
"""Initialize self.
Args:
n (int): Number of samples.
d (int): Number of nodes.
graph_type ('ER' or 'SF'): Type of graph.
degree (int): Degree of graph.
noise_type ('gaussian_ev', 'gaussian_nv', 'exponential', 'gumbel'): Type of noise.
B_scale (float): Scaling factor for range of B.
seed (int): Random seed. Default: 1.
"""
self.n = n
self.d = d
self.graph_type = graph_type
self.degree = degree
self.noise_type = noise_type
self.B_ranges = ((B_scale * -2.0, B_scale * -0.5),
(B_scale * 0.5, B_scale * 2.0))
self.rs = np.random.RandomState(seed) # Reproducibility
self._setup()
self._logger.debug("Finished setting up dataset class.")
def _setup(self):
"""Generate B_bin, B and X."""
self.B_bin = SyntheticDataset.simulate_random_dag(self.d, self.degree,
self.graph_type, self.rs)
self.B = SyntheticDataset.simulate_weight(self.B_bin, self.B_ranges, self.rs)
self.X = SyntheticDataset.simulate_linear_sem(self.B, self.n, self.noise_type, self.rs)
assert is_dag(self.B)
@staticmethod
def simulate_er_dag(d, degree, rs=np.random.RandomState(1)):
"""Simulate ER DAG using NetworkX package.
Args:
d (int): Number of nodes.
degree (int): Degree of graph.
rs (numpy.random.RandomState): Random number generator.
Default: np.random.RandomState(1).
Returns:
numpy.ndarray: [d, d] binary adjacency matrix of DAG.
"""
def _get_acyclic_graph(B_und):
return np.tril(B_und, k=-1)
def _graph_to_adjmat(G):
return nx.to_numpy_matrix(G)
p = float(degree) / (d - 1)
G_und = nx.generators.erdos_renyi_graph(n=d, p=p, seed=rs)
B_und_bin = _graph_to_adjmat(G_und) # Undirected
B_bin = _get_acyclic_graph(B_und_bin)
return B_bin
@staticmethod
def simulate_sf_dag(d, degree):
"""Simulate ER DAG using igraph package.
Args:
d (int): Number of nodes.
degree (int): Degree of graph.
Returns:
numpy.ndarray: [d, d] binary adjacency matrix of DAG.
"""
def _graph_to_adjmat(G):
return np.array(G.get_adjacency().data)
m = int(round(degree / 2))
# igraph does not allow passing RandomState object
G = ig.Graph.Barabasi(n=d, m=m, directed=True)
B_bin = np.array(G.get_adjacency().data)
return B_bin
@staticmethod
def simulate_random_dag(d, degree, graph_type, rs=np.random.RandomState(1)):
"""Simulate random DAG.
Args:
d (int): Number of nodes.
degree (int): Degree of graph.
graph_type ('ER' or 'SF'): Type of graph.
rs (numpy.random.RandomState): Random number generator.
Default: np.random.RandomState(1).
Returns:
numpy.ndarray: [d, d] binary adjacency matrix of DAG.
"""
def _random_permutation(B_bin):
# np.random.permutation permutes first axis only
P = rs.permutation(np.eye(B_bin.shape[0]))
return P.T @ B_bin @ P
if graph_type == 'ER':
B_bin = SyntheticDataset.simulate_er_dag(d, degree, rs)
elif graph_type == 'SF':
B_bin = SyntheticDataset.simulate_sf_dag(d, degree)
else:
raise ValueError("Unknown graph type.")
return _random_permutation(B_bin)
@staticmethod
def simulate_weight(B_bin, B_ranges, rs=np.random.RandomState(1)):
"""Simulate the weights of B_bin.
Args:
B_bin (numpy.ndarray): [d, d] binary adjacency matrix of DAG.
B_ranges (tuple): Disjoint weight ranges.
rs (numpy.random.RandomState): Random number generator.
Default: np.random.RandomState(1).
Returns:
numpy.ndarray: [d, d] weighted adjacency matrix of DAG.
"""
B = np.zeros(B_bin.shape)
S = rs.randint(len(B_ranges), size=B.shape) # Which range
for i, (low, high) in enumerate(B_ranges):
U = rs.uniform(low=low, high=high, size=B.shape)
B += B_bin * (S == i) * U
return B
@staticmethod
def simulate_linear_sem(B, n, noise_type, rs=np.random.RandomState(1)):
"""Simulate samples from linear SEM with specified type of noise.
Args:
B (numpy.ndarray): [d, d] weighted adjacency matrix of DAG.
n (int): Number of samples.
noise_type ('gaussian_ev', 'gaussian_nv', 'exponential', 'gumbel'): Type of noise.
rs (numpy.random.RandomState): Random number generator.
Default: np.random.RandomState(1).
Returns:
numpy.ndarray: [n, d] data matrix.
"""
def _simulate_single_equation(X, B_i):
"""Simulate samples from linear SEM for the i-th node.
Args:
X (numpy.ndarray): [n, number of parents] data matrix.
B_i (numpy.ndarray): [d,] weighted vector for the i-th node.
Returns:
numpy.ndarray: [n,] data matrix.
"""
if noise_type == 'gaussian_ev':
# Gaussian noise with equal variances
N_i = rs.normal(scale=1.0, size=n)
elif noise_type == 'gaussian_nv':
# Gaussian noise with non-equal variances
scale = rs.uniform(low=1.0, high=2.0)
N_i = rs.normal(scale=scale, size=n)
elif noise_type == 'exponential':
# Exponential noise
N_i = rs.exponential(scale=1.0, size=n)
elif noise_type == 'gumbel':
# Gumbel noise
N_i = rs.gumbel(scale=1.0, size=n)
else:
raise ValueError("Unknown noise type.")
return X @ B_i + N_i
d = B.shape[0]
X = np.zeros([n, d])
G = nx.DiGraph(B)
ordered_vertices = list(nx.topological_sort(G))
assert len(ordered_vertices) == d
for i in ordered_vertices:
parents = list(G.predecessors(i))
X[:, i] = _simulate_single_equation(X[:, parents], B[parents, i])
return X
if __name__ == '__main__':
n, d = 1000, 20
graph_type, degree = 'ER', 4 # ER2 graph
B_scale = 1.0
noise_type = 'gaussian_ev'
dataset = SyntheticDataset(n, d, graph_type, degree,
noise_type, B_scale, seed=1)
print("dataset.X.shape: {}".format(dataset.X.shape))
print("dataset.B.shape: {}".format(dataset.B.shape))
print("dataset.B_bin.shape: {}".format(dataset.B.shape))