forked from tensorflow/hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
estimator_test.py
167 lines (132 loc) · 6.05 KB
/
estimator_test.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tensorflow_hub.estimator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow_hub import tf_v1
_TEXT_FEATURE_NAME = "text"
_EXPORT_MODULE_NAME = "embedding-text"
def _input_fn():
"""An input fn."""
features = {
_TEXT_FEATURE_NAME: tf.constant([
"Example 1 feature", "Example 2"]),
}
labels = tf.constant([False, True])
return features, labels
def _serving_input_fn():
"""A serving input fn."""
text_features = tf_v1.placeholder(dtype=tf.string, shape=[None])
return tf_v1.estimator.export.ServingInputReceiver(
features={_TEXT_FEATURE_NAME: text_features},
receiver_tensors=text_features)
def text_module_fn():
weights = tf_v1.get_variable(
"weights", dtype=tf.float32, shape=[100, 10])
# initializer=tf.random_uniform_initializer())
text = tf_v1.placeholder(tf.string, shape=[None])
hash_buckets = tf_v1.string_to_hash_bucket_fast(text, weights.get_shape()[0])
embeddings = tf_v1.gather(weights, hash_buckets)
hub.add_signature(inputs=text, outputs=embeddings)
def _get_model_fn(register_module=False):
def _model_fn(features, labels, mode):
"""A model_fn that uses a mock TF-Hub module."""
del labels
spec = hub.create_module_spec(text_module_fn)
embedding = hub.Module(spec)
if register_module:
hub.register_module_for_export(embedding, _EXPORT_MODULE_NAME)
predictions = embedding(features[_TEXT_FEATURE_NAME])
loss = tf.constant(0.0)
global_step = tf_v1.train.get_global_step()
train_op = tf_v1.assign_add(global_step, 1)
return tf_v1.estimator.EstimatorSpec(
mode=mode,
predictions=predictions,
loss=loss,
train_op=train_op)
return _model_fn
class EstimatorTest(tf.test.TestCase):
def testLatestModuleExporterDirectly(self):
model_dir = tempfile.mkdtemp(dir=self.get_temp_dir())
export_base_dir = os.path.join(
tempfile.mkdtemp(dir=self.get_temp_dir()), "export")
estimator = tf_v1.estimator.Estimator(
_get_model_fn(register_module=True), model_dir=model_dir)
estimator.train(input_fn=_input_fn, steps=1)
exporter = hub.LatestModuleExporter("exporter_name", _serving_input_fn)
export_dir = exporter.export(estimator=estimator,
export_path=export_base_dir,
eval_result=None,
is_the_final_export=None)
# Check that a timestamped directory is created in the expected location.
timestamp_dirs = tf_v1.gfile.ListDirectory(export_base_dir)
self.assertEquals(1, len(timestamp_dirs))
self.assertEquals(
tf.compat.as_bytes(os.path.join(export_base_dir, timestamp_dirs[0])),
tf.compat.as_bytes(export_dir))
# Check the timestamped directory containts the exported modules inside.
expected_module_dir = os.path.join(
tf.compat.as_bytes(export_dir),
tf.compat.as_bytes(_EXPORT_MODULE_NAME))
self.assertTrue(tf_v1.gfile.IsDirectory(expected_module_dir))
def test_latest_module_exporter_with_no_modules(self):
model_dir = tempfile.mkdtemp(dir=self.get_temp_dir())
export_base_dir = os.path.join(tempfile.mkdtemp(dir=self.get_temp_dir()),
"export")
self.assertFalse(tf_v1.gfile.Exists(export_base_dir))
estimator = tf_v1.estimator.Estimator(
_get_model_fn(register_module=False), model_dir=model_dir)
estimator.train(input_fn=_input_fn, steps=1)
exporter = hub.LatestModuleExporter("exporter_name", _serving_input_fn)
export_dir = exporter.export(estimator=estimator,
export_path=export_base_dir,
eval_result=None,
is_the_final_export=None)
# Check the result.
self.assertIsNone(export_dir)
# Check that a no directory has been created in the expected location.
self.assertFalse(tf_v1.gfile.Exists(export_base_dir))
def test_latest_module_exporter_with_eval_spec(self):
model_dir = tempfile.mkdtemp(dir=self.get_temp_dir())
estimator = tf_v1.estimator.Estimator(
_get_model_fn(register_module=True), model_dir=model_dir)
exporter = hub.LatestModuleExporter(
"tf_hub", _serving_input_fn, exports_to_keep=2)
estimator.train(_input_fn, max_steps=1)
export_base_dir = os.path.join(model_dir, "export", "tf_hub")
exporter.export(estimator, export_base_dir)
timestamp_dirs = tf_v1.gfile.ListDirectory(export_base_dir)
self.assertEquals(1, len(timestamp_dirs))
oldest_timestamp = timestamp_dirs[0]
expected_module_dir = os.path.join(export_base_dir,
timestamp_dirs[0],
_EXPORT_MODULE_NAME)
self.assertTrue(tf_v1.gfile.IsDirectory(expected_module_dir))
exporter.export(estimator, export_base_dir)
timestamp_dirs = tf_v1.gfile.ListDirectory(export_base_dir)
self.assertEquals(2, len(timestamp_dirs))
# Triggering yet another export should clean the oldest export.
exporter.export(estimator, export_base_dir)
timestamp_dirs = tf_v1.gfile.ListDirectory(export_base_dir)
self.assertEquals(2, len(timestamp_dirs))
self.assertFalse(oldest_timestamp in timestamp_dirs)
if __name__ == "__main__":
tf.test.main()