• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""A simple functional keras model with one layer."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21import numpy as np
22
23from tensorflow.python import keras
24from tensorflow.python.distribute.model_collection import model_collection_base
25from tensorflow.python.eager import def_function
26from tensorflow.python.framework import constant_op
27from tensorflow.python.framework import dtypes
28from tensorflow.python.keras.optimizer_v2 import gradient_descent
29from tensorflow.python.module import module
30from tensorflow.python.ops import variables
31
32_BATCH_SIZE = 10
33
34
35def _get_data_for_simple_models():
36  x_train = constant_op.constant(np.random.rand(1000, 3), dtype=dtypes.float32)
37  y_train = constant_op.constant(np.random.rand(1000, 5), dtype=dtypes.float32)
38  x_predict = constant_op.constant(
39      np.random.rand(1000, 3), dtype=dtypes.float32)
40
41  return x_train, y_train, x_predict
42
43
44class SimpleFunctionalModel(model_collection_base.ModelAndInput):
45  """A simple functinal model and its inputs."""
46
47  def get_model(self, **kwargs):
48    output_name = 'output_layer'
49
50    x = keras.layers.Input(shape=(3,), dtype=dtypes.float32)
51    y = keras.layers.Dense(5, dtype=dtypes.float32, name=output_name)(x)
52
53    model = keras.Model(inputs=x, outputs=y)
54    optimizer = gradient_descent.SGD(learning_rate=0.001)
55    experimental_run_tf_function = kwargs.pop('experimental_run_tf_function',
56                                              None)
57    assert experimental_run_tf_function is not None
58    model.compile(
59        loss='mse',
60        metrics=['mae'],
61        optimizer=optimizer,
62        experimental_run_tf_function=experimental_run_tf_function)
63
64    return model
65
66  def get_data(self):
67    return _get_data_for_simple_models()
68
69  def get_batch_size(self):
70    return _BATCH_SIZE
71
72
73class SimpleSequentialModel(model_collection_base.ModelAndInput):
74  """A simple sequential model and its inputs."""
75
76  def get_model(self, **kwargs):
77    output_name = 'output_layer'
78
79    model = keras.Sequential()
80    y = keras.layers.Dense(
81        5, dtype=dtypes.float32, name=output_name, input_dim=3)
82    model.add(y)
83    optimizer = gradient_descent.SGD(learning_rate=0.001)
84    experimental_run_tf_function = kwargs.pop('experimental_run_tf_function',
85                                              None)
86    assert experimental_run_tf_function is not None
87    model.compile(
88        loss='mse',
89        metrics=['mae'],
90        optimizer=optimizer,
91        experimental_run_tf_function=experimental_run_tf_function)
92
93    return model
94
95  def get_data(self):
96    return _get_data_for_simple_models()
97
98  def get_batch_size(self):
99    return _BATCH_SIZE
100
101
102class _SimpleModel(keras.Model):
103
104  def __init__(self):
105    super(_SimpleModel, self).__init__()
106    self._dense_layer = keras.layers.Dense(5, dtype=dtypes.float32)
107
108  def call(self, inputs):
109    return {'output_layer': self._dense_layer(inputs)}
110
111
112class SimpleSubclassModel(model_collection_base.ModelAndInput):
113  """A simple subclass model and its data."""
114
115  def get_model(self, **kwargs):
116    model = _SimpleModel()
117    optimizer = gradient_descent.SGD(learning_rate=0.001)
118    experimental_run_tf_function = kwargs.pop('experimental_run_tf_function',
119                                              None)
120    assert experimental_run_tf_function is not None
121    model.compile(
122        loss='mse',
123        metrics=['mae'],
124        cloning=False,
125        optimizer=optimizer,
126        experimental_run_tf_function=experimental_run_tf_function)
127
128    return model
129
130  def get_data(self):
131    return _get_data_for_simple_models()
132
133  def get_batch_size(self):
134    return _BATCH_SIZE
135
136
137class _SimpleModule(module.Module):
138
139  def __init__(self):
140    self.v = variables.Variable(3.0)
141
142  @def_function.function
143  def __call__(self, x):
144    return self.v * x
145
146
147class SimpleTFModuleModel(model_collection_base.ModelAndInput):
148  """A simple model based on tf.Module and its data."""
149
150  def get_model(self, **kwargs):
151    model = _SimpleModule()
152    return model
153
154  def get_data(self):
155    return _get_data_for_simple_models()
156
157  def get_batch_size(self):
158    return _BATCH_SIZE
159