• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2016 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"""Grid search tests."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21import os
22import random
23
24from tensorflow.contrib.learn.python import learn
25from tensorflow.python.platform import test
26
27HAS_SKLEARN = os.environ.get('TENSORFLOW_SKLEARN', False)
28if HAS_SKLEARN:
29  try:
30    # pylint: disable=g-import-not-at-top
31    from sklearn import datasets
32    from sklearn.grid_search import GridSearchCV
33    from sklearn.metrics import accuracy_score
34  except ImportError:
35    HAS_SKLEARN = False
36
37
38class GridSearchTest(test.TestCase):
39  """Grid search tests."""
40
41  def testIrisDNN(self):
42    if HAS_SKLEARN:
43      random.seed(42)
44      iris = datasets.load_iris()
45      feature_columns = learn.infer_real_valued_columns_from_input(iris.data)
46      classifier = learn.DNNClassifier(
47          feature_columns=feature_columns,
48          hidden_units=[10, 20, 10],
49          n_classes=3)
50      grid_search = GridSearchCV(
51          classifier, {'hidden_units': [[5, 5], [10, 10]]},
52          scoring='accuracy',
53          fit_params={'steps': [50]})
54      grid_search.fit(iris.data, iris.target)
55      score = accuracy_score(iris.target, grid_search.predict(iris.data))
56      self.assertGreater(score, 0.5, 'Failed with score = {0}'.format(score))
57
58
59if __name__ == '__main__':
60  test.main()
61