-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathtutorial15-customizing-modelfit.py
82 lines (61 loc) · 2.21 KB
/
tutorial15-customizing-modelfit.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
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(-1, 28, 28, 1).astype("float32") / 255.0
x_test = x_test.reshape(-1, 28, 28, 1).astype("float32") / 255.0
model = keras.Sequential(
[
layers.Input(shape=(28, 28, 1)),
layers.Conv2D(64, (3, 3), padding="same"),
layers.ReLU(),
layers.Conv2D(128, (3, 3), padding="same"),
layers.ReLU(),
layers.Flatten(),
layers.Dense(10),
],
name="model",
)
class CustomFit(keras.Model):
def __init__(self, model):
super(CustomFit, self).__init__()
self.model = model
def compile(self, optimizer, loss):
super(CustomFit, self).compile()
self.optimizer = optimizer
self.loss = loss
def train_step(self, data):
x, y = data
with tf.GradientTape() as tape:
# Caclulate predictions
y_pred = self.model(x, training=True)
# Loss
loss = self.loss(y, y_pred)
# Gradients
training_vars = self.trainable_variables
gradients = tape.gradient(loss, training_vars)
# Step with optimizer
self.optimizer.apply_gradients(zip(gradients, training_vars))
acc_metric.update_state(y, y_pred)
return {"loss": loss, "accuracy": acc_metric.result()}
def test_step(self, data):
# Unpack the data
x, y = data
# Compute predictions
y_pred = self.model(x, training=False)
# Updates the metrics tracking the loss
loss = self.loss(y, y_pred)
# Update the metrics.
acc_metric.update_state(y, y_pred)
return {"loss": loss, "accuracy": acc_metric.result()}
acc_metric = keras.metrics.SparseCategoricalAccuracy(name="accuracy")
training = CustomFit(model)
training.compile(
optimizer=keras.optimizers.Adam(learning_rate=3e-4),
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
)
training.fit(x_train, y_train, batch_size=64, epochs=2)
training.evaluate(x_test, y_test, batch_size=64)