wide_deep_test.py 3.85 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

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import tensorflow as tf

import wide_deep

tf.logging.set_verbosity(tf.logging.ERROR)

TEST_INPUT = ('18,Self-emp-not-inc,987,Bachelors,12,Married-civ-spouse,abc,'
    'Husband,zyx,wvu,34,56,78,tsr,<=50K')

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',
}

44
TEST_CSV = os.path.join(os.path.dirname(__file__), 'wide_deep_test.csv')
45
46
47
48
49
50
51
52
53
54
55
56


class BaseTest(tf.test.TestCase):

  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')
    with tf.gfile.Open(self.input_csv, 'w') as temp_csv:
      temp_csv.write(TEST_INPUT)

  def test_input_fn(self):
Neal Wu's avatar
Neal Wu committed
57
58
59
    dataset = wide_deep.input_fn(self.input_csv, 1, False, 1)
    features, labels = dataset.make_one_shot_iterator().get_next()

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    with tf.Session() as sess:
      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."""
    model = wide_deep.build_estimator(self.temp_dir, model_type)

    # Train for 1 step to initialize model and evaluate initial loss
    model.train(
Neal Wu's avatar
Neal Wu committed
83
        input_fn=lambda: wide_deep.input_fn(
84
            TEST_CSV, num_epochs=1, shuffle=True, batch_size=1),
85
86
        steps=1)
    initial_results = model.evaluate(
Neal Wu's avatar
Neal Wu committed
87
        input_fn=lambda: wide_deep.input_fn(
88
            TEST_CSV, num_epochs=1, shuffle=False, batch_size=1))
89

Neal Wu's avatar
Neal Wu committed
90
    # Train for 100 epochs at batch size 3 and evaluate final loss
91
    model.train(
Neal Wu's avatar
Neal Wu committed
92
        input_fn=lambda: wide_deep.input_fn(
Neal Wu's avatar
Neal Wu committed
93
            TEST_CSV, num_epochs=100, shuffle=True, batch_size=3))
94
    final_results = model.evaluate(
Neal Wu's avatar
Neal Wu committed
95
        input_fn=lambda: wide_deep.input_fn(
96
            TEST_CSV, num_epochs=1, shuffle=False, batch_size=1))
97
98
99

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

    # Ensure loss has decreased, while accuracy and both AUCs have increased.
102
    self.assertLess(final_results['loss'], initial_results['loss'])
Neal Wu's avatar
Neal Wu committed
103
104
105
106
    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'])
107
108
109
110
111
112
113

  def test_wide_deep_estimator_training(self):
    self.build_and_test_estimator('wide_deep')


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