-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathcustom-layers.py
51 lines (40 loc) · 1.34 KB
/
custom-layers.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
import tensorflow as tf
from tensorflow import keras
import numpy as np
data_x = np.random.normal(size=[1000, 1])
noise = np.random.normal(size=[1000, 1]) * 0.2
data_y = data_x * 3. + 2. + noise
train_x, train_y = data_x[:900], data_y[:900]
test_x, test_y = data_x[900:], data_y[900:]
class MyLayer(keras.layers.Layer):
def __init__(self, num_outputs):
super().__init__()
self.num_outputs = num_outputs
self.w = None
self.b = None
def build(self, input_shape):
self.w = self.add_weight(
name="w",
shape=[int(input_shape[-1]), self.num_outputs],
dtype=tf.float32,
initializer=keras.initializers.RandomNormal(),
)
self.b = self.add_weight(
name="b",
shape=[1, self.num_outputs],
dtype=tf.float32,
initializer=keras.initializers.Constant(0.1),
)
def call(self, inputs, **kwargs):
return tf.matmul(inputs, self.w) + self.b
model = keras.models.Sequential([
MyLayer(10),
keras.layers.Dense(1),
])
model.compile(
optimizer=keras.optimizers.SGD(0.01),
loss=keras.losses.MeanSquaredError(),
metrics=[keras.metrics.MeanSquaredError()],
)
model.fit(train_x, train_y, batch_size=32, epochs=3, validation_split=0.2, shuffle=True)
model.evaluate(test_x, test_y, verbose=1)