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"""Example of DNNRegressor for Housing dataset.""" 15 16from __future__ import absolute_import 17from __future__ import division 18from __future__ import print_function 19 20import numpy as np 21from sklearn import datasets 22from sklearn import metrics 23from sklearn import model_selection 24from sklearn import preprocessing 25 26import tensorflow as tf 27 28 29def main(unused_argv): 30 # Load dataset 31 boston = datasets.load_boston() 32 x, y = boston.data, boston.target 33 34 # Split dataset into train / test 35 x_train, x_test, y_train, y_test = model_selection.train_test_split( 36 x, y, test_size=0.2, random_state=42) 37 38 # Scale data (training set) to 0 mean and unit standard deviation. 39 scaler = preprocessing.StandardScaler() 40 x_train = scaler.fit_transform(x_train) 41 42 # Build 2 layer fully connected DNN with 10, 10 units respectively. 43 feature_columns = [ 44 tf.feature_column.numeric_column('x', shape=np.array(x_train).shape[1:])] 45 regressor = tf.estimator.DNNRegressor( 46 feature_columns=feature_columns, hidden_units=[10, 10]) 47 48 # Train. 49 train_input_fn = tf.estimator.inputs.numpy_input_fn( 50 x={'x': x_train}, y=y_train, batch_size=1, num_epochs=None, shuffle=True) 51 regressor.train(input_fn=train_input_fn, steps=2000) 52 53 # Predict. 54 x_transformed = scaler.transform(x_test) 55 test_input_fn = tf.estimator.inputs.numpy_input_fn( 56 x={'x': x_transformed}, y=y_test, num_epochs=1, shuffle=False) 57 predictions = regressor.predict(input_fn=test_input_fn) 58 y_predicted = np.array(list(p['predictions'] for p in predictions)) 59 y_predicted = y_predicted.reshape(np.array(y_test).shape) 60 61 # Score with sklearn. 62 score_sklearn = metrics.mean_squared_error(y_predicted, y_test) 63 print('MSE (sklearn): {0:f}'.format(score_sklearn)) 64 65 # Score with tensorflow. 66 scores = regressor.evaluate(input_fn=test_input_fn) 67 print('MSE (tensorflow): {0:f}'.format(scores['average_loss'])) 68 69 70if __name__ == '__main__': 71 tf.app.run() 72