2023-04-17 21:56:37 +00:00
|
|
|
import numpy as np
|
|
|
|
|
2023-04-18 04:26:04 +00:00
|
|
|
from keras_core import backend
|
2023-04-19 20:50:22 +00:00
|
|
|
from keras_core import initializers
|
2023-04-17 21:56:37 +00:00
|
|
|
from keras_core import layers
|
|
|
|
from keras_core import losses
|
2023-04-17 22:41:48 +00:00
|
|
|
from keras_core import metrics
|
|
|
|
from keras_core import optimizers
|
|
|
|
from keras_core import testing
|
2023-04-19 20:50:22 +00:00
|
|
|
|
|
|
|
if backend.backend() == "jax":
|
|
|
|
from keras_core.backend.jax.trainer import Trainer
|
|
|
|
else:
|
|
|
|
from keras_core.backend.tensorflow.trainer import Trainer
|
2023-04-17 21:56:37 +00:00
|
|
|
|
|
|
|
|
|
|
|
# A model is just a layer mixed in with a Trainer.
|
2023-04-19 20:50:22 +00:00
|
|
|
class ExampleModel(layers.Dense, Trainer):
|
2023-04-17 21:56:37 +00:00
|
|
|
def __init__(self, units):
|
2023-04-19 20:50:22 +00:00
|
|
|
layers.Dense.__init__(
|
|
|
|
self,
|
|
|
|
units=units,
|
|
|
|
use_bias=False,
|
|
|
|
kernel_initializer=initializers.Ones(),
|
|
|
|
)
|
2023-04-18 00:47:22 +00:00
|
|
|
Trainer.__init__(self)
|
2023-04-17 21:56:37 +00:00
|
|
|
|
|
|
|
|
2023-04-19 20:50:22 +00:00
|
|
|
class TestTrainer(testing.TestCase):
|
2023-04-17 21:56:37 +00:00
|
|
|
def _test_basic_flow(self, run_eagerly, jit_compile):
|
2023-04-19 20:50:22 +00:00
|
|
|
model = ExampleModel(units=3)
|
|
|
|
x = np.ones((100, 4))
|
|
|
|
y = np.zeros((100, 3))
|
2023-04-17 21:56:37 +00:00
|
|
|
batch_size = 16
|
2023-04-19 20:50:22 +00:00
|
|
|
epochs = 3
|
2023-04-17 21:56:37 +00:00
|
|
|
|
2023-04-17 22:41:48 +00:00
|
|
|
model.compile(
|
|
|
|
optimizer=optimizers.SGD(),
|
|
|
|
loss=losses.MeanSquaredError(),
|
|
|
|
metrics=[metrics.MeanSquaredError()],
|
|
|
|
run_eagerly=run_eagerly,
|
|
|
|
jit_compile=jit_compile,
|
|
|
|
)
|
2023-04-17 22:18:27 +00:00
|
|
|
history = model.fit(x, y, batch_size=batch_size, epochs=epochs)
|
2023-04-19 20:50:22 +00:00
|
|
|
history = history.history
|
|
|
|
self.assertIn("loss", history)
|
|
|
|
self.assertIn("mean_squared_error", history)
|
|
|
|
self.assertAllClose(
|
|
|
|
history["mean_squared_error"], [13.938, 9.547, 6.539], atol=1e-2
|
|
|
|
)
|
2023-04-17 21:56:37 +00:00
|
|
|
|
|
|
|
def test_basic_flow_eager(self):
|
|
|
|
self._test_basic_flow(run_eagerly=True, jit_compile=False)
|
|
|
|
|
|
|
|
def test_basic_flow_graph_fn(self):
|
|
|
|
self._test_basic_flow(run_eagerly=False, jit_compile=False)
|
|
|
|
|
|
|
|
def test_basic_flow_jit(self):
|
|
|
|
self._test_basic_flow(run_eagerly=False, jit_compile=True)
|