StevenJingfeng commited on
Commit
0662e7d
·
verified ·
1 Parent(s): 9bbcb68

Upload NAM_models.py

Browse files
Files changed (1) hide show
  1. code/NAM_models.py +354 -0
code/NAM_models.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Google Research Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Lint as: python3
17
+ """Neural net models for tabular datasets."""
18
+
19
+ from typing import Union, List
20
+ import numpy as np
21
+ import tensorflow as tf
22
+
23
+ TfInput = Union[np.ndarray, tf.Tensor]
24
+
25
+
26
+ def exu(x, weight, bias):
27
+ """ExU hidden unit modification."""
28
+ return tf.exp(weight) * (x - bias)
29
+
30
+
31
+ # Activation Functions
32
+ def relu(x, weight, bias):
33
+ """ReLU activation."""
34
+ return tf.nn.relu(weight * (x - bias))
35
+
36
+
37
+ def relu_n(x, n = 1):
38
+ """ReLU activation clipped at n."""
39
+ return tf.clip_by_value(x, 0, n)
40
+
41
+
42
+ class ActivationLayer(tf.keras.layers.Layer):
43
+ """Custom activation Layer to support ExU hidden units."""
44
+
45
+ def __init__(self,
46
+ num_units,
47
+ name = None,
48
+ activation = 'exu',
49
+ trainable = True):
50
+ """Initializes ActivationLayer hyperparameters.
51
+
52
+ Args:
53
+ num_units: Number of hidden units in the layer.
54
+ name: The name of the layer.
55
+ activation: Activation to use. The default value of `None` corresponds to
56
+ using the ReLU-1 activation with ExU units while `relu` would use
57
+ standard hidden units with ReLU activation.
58
+ trainable: Whether the layer parameters are trainable or not.
59
+ """
60
+ super(ActivationLayer, self).__init__(trainable=trainable, name=name)
61
+ self.num_units = num_units
62
+ self._trainable = trainable
63
+ if activation == 'relu':
64
+ self._activation = relu
65
+ self._beta_initializer = 'glorot_uniform'
66
+ elif activation == 'exu':
67
+ self._activation = lambda x, weight, bias: relu_n(exu(x, weight, bias))
68
+ self._beta_initializer = tf.initializers.truncated_normal(
69
+ mean=4.0, stddev=0.5)
70
+ else:
71
+ raise ValueError('{} is not a valid activation'.format(activation))
72
+
73
+ def build(self, input_shape):
74
+ """Builds the layer weight and bias parameters."""
75
+ self._beta = self.add_weight(
76
+ name='beta',
77
+ shape=[input_shape[-1], self.num_units],
78
+ initializer=self._beta_initializer,
79
+ trainable=self._trainable)
80
+ self._c = self.add_weight(
81
+ name='c',
82
+ shape=[1, self.num_units],
83
+ initializer=tf.initializers.truncated_normal(stddev=0.5),
84
+ trainable=self._trainable)
85
+ super(ActivationLayer, self).build(input_shape)
86
+
87
+ @tf.function
88
+ def call(self, x):
89
+ """Computes the output activations."""
90
+ center = tf.tile(self._c, [tf.shape(x)[0], 1])
91
+ out = self._activation(x, self._beta, center)
92
+ return out
93
+
94
+
95
+ class FeatureNN(tf.keras.layers.Layer):
96
+ """Neural Network model for each individual feature.
97
+
98
+ Attributes:
99
+ hidden_layers: A list containing hidden layers. The first layer is an
100
+ `ActivationLayer` containing `num_units` neurons with specified
101
+ `activation`. If `shallow` is False, then it additionally contains 2
102
+ tf.keras.layers.Dense ReLU layers with 64, 32 hidden units respectively.
103
+ linear: Fully connected layer.
104
+ """
105
+
106
+ def __init__(self,
107
+ num_units,
108
+ dropout = 0.5,
109
+ trainable = True,
110
+ shallow = True,
111
+ feature_num = 0,
112
+ name_scope = 'model',
113
+ activation = 'exu'):
114
+ """Initializes FeatureNN hyperparameters.
115
+
116
+ Args:
117
+ num_units: Number of hidden units in first hidden layer.
118
+ dropout: Coefficient for dropout regularization.
119
+ trainable: Whether the FeatureNN parameters are trainable or not.
120
+ shallow: If True, then a shallow network with a single hidden layer is
121
+ created, otherwise, a network with 3 hidden layers is created.
122
+ feature_num: Feature Index used for naming the hidden layers.
123
+ name_scope: TF name scope str for the model.
124
+ activation: Activation and type of hidden unit(ExUs/Standard) used in the
125
+ first hidden layer.
126
+ """
127
+ super(FeatureNN, self).__init__()
128
+ self._num_units = num_units
129
+ self._dropout = dropout
130
+ self._trainable = trainable
131
+ self._tf_name_scope = name_scope
132
+ self._feature_num = feature_num
133
+ self._shallow = shallow
134
+ self._activation = activation
135
+
136
+ def build(self, input_shape):
137
+ """Builds the feature net layers."""
138
+ self.hidden_layers = [
139
+ ]
140
+ if not self._shallow:
141
+ self._h1 = tf.keras.layers.Dense(
142
+ 8,
143
+ activation='sigmoid',
144
+ use_bias=True,
145
+ trainable=self._trainable,
146
+ name='h1_{}'.format(self._feature_num),
147
+ kernel_initializer='glorot_uniform')
148
+
149
+ self._h2 = tf.keras.layers.Dense(
150
+ 8,
151
+ activation='relu',
152
+ use_bias=True,
153
+ trainable=self._trainable,
154
+ name='h2_{}'.format(self._feature_num),
155
+ kernel_initializer='glorot_uniform')
156
+
157
+ self._h3 = tf.keras.layers.Dense(
158
+ 8,
159
+ activation='sigmoid',
160
+ use_bias=True,
161
+ trainable=self._trainable,
162
+ name='h3_{}'.format(self._feature_num),
163
+ kernel_initializer='glorot_uniform')
164
+
165
+ self.hidden_layers += [self._h1,self._h2,self._h3]
166
+
167
+ self.linear = tf.keras.layers.Dense(
168
+ 1,
169
+ use_bias=True,
170
+ trainable=self._trainable,
171
+ name='dense_{}'.format(self._feature_num),
172
+ kernel_initializer='glorot_uniform')
173
+ super(FeatureNN, self).build(input_shape)
174
+
175
+ @tf.function
176
+ def call(self, x, training):
177
+ """Computes FeatureNN output with either evaluation or training mode."""
178
+ with tf.name_scope(self._tf_name_scope):
179
+ for l in self.hidden_layers:
180
+ x = tf.nn.dropout(
181
+ l(x), rate=tf.cond(training, lambda: self._dropout, lambda: 0.0))
182
+ x = tf.squeeze(self.linear(x), axis=1)
183
+ return x
184
+
185
+
186
+ class NAM(tf.keras.Model):
187
+ """Neural additive model.
188
+
189
+ Attributes:
190
+ feature_nns: List of FeatureNN, one per input feature.
191
+ """
192
+
193
+ def __init__(self,
194
+ num_inputs,
195
+ num_units,
196
+ trainable = True,
197
+ shallow = True,
198
+ feature_dropout = 0.0,
199
+ dropout = 0.0,
200
+ **kwargs):
201
+ """Initializes NAM hyperparameters.
202
+
203
+ Args:
204
+ num_inputs: Number of feature inputs in input data.
205
+ num_units: Number of hidden units in first layer of each feature net.
206
+ trainable: Whether the NAM parameters are trainable or not.
207
+ shallow: If True, then shallow feature nets with a single hidden layer are
208
+ created, otherwise, feature nets with 3 hidden layers are created.
209
+ feature_dropout: Coefficient for dropping out entire Feature NNs.
210
+ dropout: Coefficient for dropout within each Feature NNs.
211
+ **kwargs: Arbitrary keyword arguments. Used for passing the `activation`
212
+ function as well as the `name_scope`.
213
+ """
214
+ super(NAM, self).__init__()
215
+ self._num_inputs = num_inputs
216
+ if isinstance(num_units, list):
217
+ self._num_units = num_units
218
+ elif isinstance(num_units, int):
219
+ self._num_units = [num_units for _ in range(self._num_inputs)]
220
+ self._trainable = trainable
221
+ self._shallow = shallow
222
+ self._feature_dropout = feature_dropout
223
+ self._dropout = dropout
224
+ self._kwargs = kwargs
225
+
226
+ def build(self, input_shape):
227
+ """Builds the FeatureNNs on the first call."""
228
+ self.feature_nns = [None] * self._num_inputs
229
+ for i in range(self._num_inputs):
230
+ self.feature_nns[i] = FeatureNN(
231
+ num_units=self._num_units[i],
232
+ dropout=self._dropout,
233
+ trainable=self._trainable,
234
+ shallow=self._shallow,
235
+ feature_num=i)
236
+ self._bias = self.add_weight(
237
+ name='bias',
238
+ initializer=tf.keras.initializers.Zeros(),
239
+ shape=(1,),
240
+ trainable=self._trainable)
241
+ self._true = tf.constant(True, dtype=tf.bool)
242
+ self._false = tf.constant(False, dtype=tf.bool)
243
+
244
+ def call(self, x, training = True):
245
+ """Computes NAM output by adding the outputs of individual feature nets."""
246
+ individual_outputs = self.calc_outputs(x, training=training)
247
+ stacked_out = tf.stack(individual_outputs, axis=-1)
248
+ training = self._true if training else self._false
249
+ dropout_out = tf.nn.dropout(
250
+ stacked_out,
251
+ rate=tf.cond(training, lambda: self._feature_dropout, lambda: 0.0))
252
+ out = tf.reduce_sum(dropout_out, axis=-1)
253
+ return out + self._bias
254
+
255
+ def get_loss(self, x,true_value,monotonic_feature,individual_output,alpha_1,pair,pair1,pair2,pair3,alpha_2,pair_s, pair_s1,alpha_3,num_fea):
256
+ output=self.call(x,training=True)
257
+ output=tf.reshape(output, len(x))
258
+ true_value=tf.cast(true_value,tf.float32)
259
+
260
+ #Binary cross entropy
261
+ BCE=-tf.reduce_sum(tf.multiply(tf.math.log(output+0.00001),true_value)+tf.multiply((1-true_value),tf.math.log(1-output+0.00001)))/len(x)
262
+ MSE= tf.reduce_mean(tf.square(output - true_value))
263
+ print(MSE)
264
+ #Punishment
265
+
266
+
267
+ puni_2=0
268
+ for i in range(len(pair)):
269
+ temp=np.zeros(len(x[0]))
270
+ temp1=np.zeros(len(x[0]))
271
+
272
+ temp[0:num_fea]=pair[i]
273
+ temp1[0:num_fea]=pair1[i]
274
+
275
+
276
+ out=self.calc_outputs([temp], training=True)
277
+ out1=self.calc_outputs([temp1], training=True)
278
+
279
+
280
+ puni_2+=max(out1[0]-out[0],0)
281
+
282
+ punish_2=alpha_2*puni_2
283
+ print("loss of strong pairwise monotonicity",punish_2)
284
+
285
+ ans = tf.constant(MSE+punish_2)
286
+ print("overall loss",ans)
287
+ return ans
288
+
289
+ def get_grad(self, x,true_value,monotonic_feature,individual_output,alpha_1,pair,pair1,pair2,pair3,alpha_2,pair_s,pair_s1,alpha_3,num_fea):
290
+ with tf.GradientTape() as tape:
291
+ tape.watch(self.variables)
292
+ L = self.get_loss(x,true_value,monotonic_feature,individual_output,alpha_1,pair,pair1,pair2,pair3,alpha_2,pair_s,pair_s1,alpha_3,num_fea)
293
+ g = tape.gradient(L, self.variables)
294
+ return g
295
+
296
+
297
+ def network_learn(self, x,true_value,monotonic_feature,individual_output,alpha_1,pair,pair1,pair2,pair3,alpha_2,pair_s, pair_s1,alpha_3,learning_r,num_fea):
298
+ g = self.get_grad(x,true_value,monotonic_feature,individual_output,alpha_1,pair,pair1,pair2,pair3,alpha_2,pair_s, pair_s1,alpha_3,num_fea)
299
+ tf.keras.optimizers.Adam(learning_rate=learning_r).apply_gradients(zip(g, self.variables))
300
+
301
+
302
+ def calc_outputs(self, x, training = True):
303
+ """Returns the output computed by each feature net."""
304
+ training = self._true if training else self._false
305
+ list_x = tf.split(x, list(self._kwargs['kwargs']), axis=-1)
306
+ return [
307
+ self.feature_nns[i](x_i, training=training)
308
+ for i, x_i in enumerate(list_x)
309
+ ]
310
+
311
+
312
+ class DNN(tf.keras.Model):
313
+ """Deep Neural Network with 10 hidden layers.
314
+
315
+ Attributes:
316
+ hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU.
317
+ linear: Fully-connected layer.
318
+ """
319
+
320
+ def __init__(self, trainable = True, dropout = 0.15):
321
+ """Creates the DNN layers.
322
+
323
+ Args:
324
+ trainable: Whether the DNN parameters are trainable or not.
325
+ dropout: Coefficient for dropout regularization.
326
+ """
327
+ super(DNN, self).__init__()
328
+ self._dropout = dropout
329
+ self.hidden_layers = [None for _ in range(10)]
330
+ for i in range(10):
331
+ self.hidden_layers[i] = tf.keras.layers.Dense(
332
+ 100,
333
+ activation='relu',
334
+ use_bias=True,
335
+ trainable=trainable,
336
+ name='dense_{}'.format(i),
337
+ kernel_initializer='he_normal')
338
+ self.linear = tf.keras.layers.Dense(
339
+ 1,
340
+ use_bias=True,
341
+ trainable=trainable,
342
+ name='linear',
343
+ kernel_initializer='he_normal')
344
+ self._true = tf.constant(True, dtype=tf.bool)
345
+ self._false = tf.constant(False, dtype=tf.bool)
346
+
347
+ def call(self, x, training = True):
348
+ """Creates the output tensor given an input."""
349
+ training = self._true if training else self._false
350
+ for l in self.hidden_layers:
351
+ x = tf.nn.dropout(
352
+ l(x), rate=tf.cond(training, lambda: self._dropout, lambda: 0.0))
353
+ x = tf.squeeze(self.linear(x), axis=-1)
354
+ return x