census_test.py 5.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Copyright 2017 The TensorFlow 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.
# ==============================================================================

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
21
import unittest
22

Karmel Allison's avatar
Karmel Allison committed
23
import tensorflow as tf  # pylint: disable=g-bad-import-order
24

25
from official.utils.misc import keras_utils
26
from official.utils.testing import integration
27
28
from official.wide_deep import census_dataset
from official.wide_deep import census_main
29

30
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
31
32

TEST_INPUT = ('18,Self-emp-not-inc,987,Bachelors,12,Married-civ-spouse,abc,'
Karmel Allison's avatar
Karmel Allison committed
33
              'Husband,zyx,wvu,34,56,78,tsr,<=50K')
34
35
36
37
38
39
40
41
42
43
44
45
46
47

TEST_INPUT_VALUES = {
    'age': 18,
    'education_num': 12,
    'capital_gain': 34,
    'capital_loss': 56,
    'hours_per_week': 78,
    'education': 'Bachelors',
    'marital_status': 'Married-civ-spouse',
    'relationship': 'Husband',
    'workclass': 'Self-emp-not-inc',
    'occupation': 'abc',
}

48
TEST_CSV = os.path.join(os.path.dirname(__file__), 'census_test.csv')
49
50
51


class BaseTest(tf.test.TestCase):
Karmel Allison's avatar
Karmel Allison committed
52
  """Tests for Wide Deep model."""
53

54
55
56
  @classmethod
  def setUpClass(cls):  # pylint: disable=invalid-name
    super(BaseTest, cls).setUpClass()
57
    census_main.define_census_flags()
58

59
60
61
62
  def setUp(self):
    # Create temporary CSV file
    self.temp_dir = self.get_temp_dir()
    self.input_csv = os.path.join(self.temp_dir, 'test.csv')
63
    with tf.io.gfile.GFile(self.input_csv, 'w') as temp_csv:
64
65
      temp_csv.write(TEST_INPUT)

66
    with tf.io.gfile.GFile(TEST_CSV, 'r') as temp_csv:
67
68
69
      test_csv_contents = temp_csv.read()

    # Used for end-to-end tests.
70
    for fname in [census_dataset.TRAINING_FILE, census_dataset.EVAL_FILE]:
71
72
      with tf.io.gfile.GFile(
          os.path.join(self.temp_dir, fname), 'w') as test_csv:
73
74
        test_csv.write(test_csv_contents)

75
  @unittest.skipIf(keras_utils.is_v2_0(), 'TF 1.0 only test.')
76
  def test_input_fn(self):
77
    dataset = census_dataset.input_fn(self.input_csv, 1, False, 1)
Neal Wu's avatar
Neal Wu committed
78
79
    features, labels = dataset.make_one_shot_iterator().get_next()

80
    with self.test_session() as sess:
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
      features, labels = sess.run((features, labels))

      # Compare the two features dictionaries.
      for key in TEST_INPUT_VALUES:
        self.assertTrue(key in features)
        self.assertEqual(len(features[key]), 1)
        feature_value = features[key][0]

        # Convert from bytes to string for Python 3.
        if isinstance(feature_value, bytes):
          feature_value = feature_value.decode()

        self.assertEqual(TEST_INPUT_VALUES[key], feature_value)

      self.assertFalse(labels)

  def build_and_test_estimator(self, model_type):
    """Ensure that model trains and minimizes loss."""
99
100
    model = census_main.build_estimator(
        self.temp_dir, model_type,
101
102
        model_column_fn=census_dataset.build_model_columns,
        inter_op=0, intra_op=0)
103
104

    # Train for 1 step to initialize model and evaluate initial loss
Karmel Allison's avatar
Karmel Allison committed
105
106
    def get_input_fn(num_epochs, shuffle, batch_size):
      def input_fn():
107
        return census_dataset.input_fn(
Karmel Allison's avatar
Karmel Allison committed
108
109
110
111
112
113
            TEST_CSV, num_epochs=num_epochs, shuffle=shuffle,
            batch_size=batch_size)
      return input_fn

    model.train(input_fn=get_input_fn(1, True, 1), steps=1)
    initial_results = model.evaluate(input_fn=get_input_fn(1, False, 1))
114

Neal Wu's avatar
Neal Wu committed
115
    # Train for 100 epochs at batch size 3 and evaluate final loss
Karmel Allison's avatar
Karmel Allison committed
116
117
    model.train(input_fn=get_input_fn(100, True, 3))
    final_results = model.evaluate(input_fn=get_input_fn(1, False, 1))
118
119
120

    print('%s initial results:' % model_type, initial_results)
    print('%s final results:' % model_type, final_results)
Neal Wu's avatar
Neal Wu committed
121
122

    # Ensure loss has decreased, while accuracy and both AUCs have increased.
123
    self.assertLess(final_results['loss'], initial_results['loss'])
Neal Wu's avatar
Neal Wu committed
124
125
126
127
    self.assertGreater(final_results['auc'], initial_results['auc'])
    self.assertGreater(final_results['auc_precision_recall'],
                       initial_results['auc_precision_recall'])
    self.assertGreater(final_results['accuracy'], initial_results['accuracy'])
128

129
  @unittest.skipIf(keras_utils.is_v2_0(), 'TF 1.0 only test.')
130
131
132
  def test_wide_deep_estimator_training(self):
    self.build_and_test_estimator('wide_deep')

133
  @unittest.skipIf(keras_utils.is_v2_0(), 'TF 1.0 only test.')
134
135
  def test_end_to_end_wide(self):
    integration.run_synthetic(
136
137
        main=census_main.main, tmp_root=self.get_temp_dir(),
        extra_flags=[
138
139
            '--data_dir', self.get_temp_dir(),
            '--model_type', 'wide',
140
            '--download_if_missing=false'
141
142
143
        ],
        synth=False, max_train=None)

144
  @unittest.skipIf(keras_utils.is_v2_0(), 'TF 1.0 only test.')
145
146
  def test_end_to_end_deep(self):
    integration.run_synthetic(
147
148
        main=census_main.main, tmp_root=self.get_temp_dir(),
        extra_flags=[
149
150
            '--data_dir', self.get_temp_dir(),
            '--model_type', 'deep',
151
            '--download_if_missing=false'
152
153
154
        ],
        synth=False, max_train=None)

155
  @unittest.skipIf(keras_utils.is_v2_0(), 'TF 1.0 only test.')
156
157
  def test_end_to_end_wide_deep(self):
    integration.run_synthetic(
158
159
        main=census_main.main, tmp_root=self.get_temp_dir(),
        extra_flags=[
160
161
            '--data_dir', self.get_temp_dir(),
            '--model_type', 'wide_deep',
162
            '--download_if_missing=false'
163
164
165
        ],
        synth=False, max_train=None)

166
167
168

if __name__ == '__main__':
  tf.test.main()