├── LICENSE ├── README.md ├── config_gpu.yaml ├── config_standard.yaml ├── data_files ├── eval.csv ├── test_instance.json └── train.csv ├── trainer ├── __init__.py ├── model.py └── task.py └── wnd_criteo.ipynb /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Wide & Deep with TensorFlow 2 | 3 | This directory contains the code for running a Wide and Deep model. It also runs in Cloud ML Engine. This code has been tested on Python 2.7 but should also run on Python 3.5 4 | 5 | Follow along the codelab here: http://bit.ly/widendeep-slides 6 | 7 | # About the dataset and model 8 | Wide and deep jointly trains wide linear models and deep neural networks -- to combine the benefits of memorization and generalization for recommender systems. See the [research paper](https://arxiv.org/abs/1606.07792) for more details. The code is based on the [TensorFlow wide and deep tutorial](https://www.tensorflow.org/tutorials/wide_and_deep/). 9 | 10 | We will use the [Kaggle Criteo Dataset](https://www.kaggle.com/c/criteo-display-ad-challenge) to predict the probability that an ad is clicked. 11 | 12 | The dataset is downloaded as part of the script (and in the cloud directly uses the copy stored online). 13 | 14 | If you wish to download a copy, the data are located here: 15 | - gs://dataset-uploader/criteo-kaggle/small_version -- 2.5MB, 10K rows 16 | - gs://dataset-uploader/criteo-kaggle/medium_version -- 273MB, 1M rows 17 | - gs://dataset-uploader/criteo-kaggle/large_version -- 2.7GB, 10M rows 18 | 19 | Each folder contains 2 files: train.csv and eval.csv 20 | 21 | The command line tool gsutil is part of the Google Cloud SDK, and comes with gcloud. 22 | No gsutil but still want to download? Replace "gs://" with 'https://storage.googleapis.com/', for example: 23 | https://storage.googleapis.com/dataset-uploader/criteo-kaggle/small_version/train.csv 24 | 25 | 26 | # Training and evaluation 27 | This repo presents 3 methods of running the model: locally, on a jupyter notebook, and on Google Cloud ML Engine. 28 | 29 | The commands below assume you are in this directory (wide_n_deep). 30 | 31 | You should move to it with `cd workshop_sections/wide_n_deep` 32 | 33 | ### Local 34 | `python trainer/task.py` 35 | 36 | ### Jupyter Notebook 37 | Run the notebook, and step through the cells. 38 | 39 | `jupyter notebook` 40 | 41 | ### Google Cloud Machine Learning Engine 42 | The workflow to run this on Cloud Machine Learning Engine is to do a local run first, then move to the cloud. 43 | 44 | #### Test it locally: 45 | $ gcloud ml-engine local train --package-path=trainer --module-name=trainer.task 46 | TensorFlow version 1.0.0 47 | model directory = models/model_WIDE_AND_DEEP_1491431579 48 | estimator built 49 | fit done 50 | evaluate done 51 | Accuracy: 0.84125 52 | Model exported to models/model_WIDE_AND_DEEP_1491431579/exports 53 | 54 | #### Run it in the cloud: 55 | Ensure you have the project you want to work in selected. You can check using `gcloud config list` 56 | 57 | If you need to set it to a new value, do so using `gcloud config set ` 58 | 59 | You should also make sure that the Cloud ML Engine API is turned on for your project. More info about getting setup is here: https://cloud.google.com/ml-engine/docs/quickstarts/command-line 60 | 61 | Next, set the following environment variables and submit a training job. 62 | 63 | gcloud config set compute/region us-central1 64 | gcloud config set compute/zone us-central1-c 65 | 66 | export PROJECT_ID=`gcloud config list project --format "value(core.project)"` 67 | export BUCKET=gs://${PROJECT_ID}-ml 68 | export JOB_NAME=widendeep_${USER}_$(date +%Y%m%d_%H%M%S) 69 | export TRAIN_PATH=${BUCKET}/${JOB_NAME} 70 | 71 | gcloud ml-engine jobs submit training ${JOB_NAME} --package-path=trainer --module-name=trainer.task --region=us-central1 --job-dir=${TRAIN_PATH} 72 | 73 | When you are ready to run it on a more power cluster, you can customize a config.yaml file. Included in this repo are 2 examples, one for the STANDARD_1 sizing, and one custom setup which includes 3 GPU-enabled machines. 74 | 75 | gcloud ml-engine jobs submit training ${JOB_NAME} --package-path=trainer --module-name=trainer.task --job-dir=${TRAIN_PATH} --config config_standard.yaml 76 | 77 | gcloud ml-engine jobs submit training ${JOB_NAME} --package-path=trainer --module-name=trainer.task --job-dir=${TRAIN_PATH} --config config_gpu.yaml 78 | 79 | 80 | You can check the status of your training job with the command: 81 | 82 | gcloud ml-engine jobs describe $JOB_NAME 83 | 84 | You can also see it's progress in your cloud console and view the logs. 85 | 86 | To run another job (in your dev workflow), simply set a new `JOB_NAME` and `TRAIN_PATH` and then re-run the `jobs.summit` call. Job names must be unique. 87 | 88 | export JOB_NAME=widendeep_${USER}_$(date +%Y%m%d_%H%M%S) 89 | export TRAIN_PATH=${BUCKET}/${JOB_NAME} 90 | gcloud ml-engine jobs submit training ${JOB_NAME} --package-path=trainer --module-name=trainer.task --region=us-central1 --job-dir=${TRAIN_PATH} 91 | 92 | 93 | # Your trained model 94 | Whether you ran your training locally or in the cloud, you should now have a set of files exported. If you ran this locally, it will be located in someplace similar to `models/model_WIDE_AND_DEEP_1234567890/exports/1234567890`. If you ran it in the cloud, it will be located in the GCS bucket that you passed. 95 | 96 | The trained model files that were exported are ready to be used for prediction. 97 | 98 | # Prediction 99 | You can run prediction jobs in Cloud ML Engine as well, using the Prediction Service. 100 | 101 | Before we begin, if you trained a model locally, you should upload the contents that were exported (something like `saved_model.pb` and a folder called `variables`) to a Google Cloud Storage location and make a note of its address (`gs:///path/to/model`) 102 | 103 | Now we are ready to create a model 104 | 105 | export MODEL_NAME='my_model' 106 | gcloud ml-engine models create $MODEL_NAME 107 | 108 | Next, create a 'version' of that model 109 | 110 | export VERSION_NAME='my_version' 111 | export DEPLOYMENT_SOURCE='gs://LOCATION_OF_MODEL_FILES' 112 | gcloud ml-engine versions create $VERSION_NAME --model $MODEL_NAME --origin $DEPLOYMENT_SOURCE 113 | 114 | Finally, make a prediction with your newly deployed version! 115 | 116 | gcloud ml-engine predict --model $MODEL_NAME --version $VERSION_NAME --json-instances test_instance.json 117 | -------------------------------------------------------------------------------- /config_gpu.yaml: -------------------------------------------------------------------------------- 1 | trainingInput: 2 | region: us-east1 3 | scaleTier: CUSTOM 4 | masterType: complex_model_m 5 | workerType: standard_gpu 6 | parameterServerType: large_model 7 | workerCount: 4 8 | parameterServerCount: 3 9 | -------------------------------------------------------------------------------- /config_standard.yaml: -------------------------------------------------------------------------------- 1 | trainingInput: 2 | scaleTier: STANDARD_1 3 | region: us-central1 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /data_files/test_instance.json: -------------------------------------------------------------------------------- 1 | {"C1": "be589b51", "C10": "3ff10fb2", "C11": "5874c9c9", "C12": "976cbd4c", "C13": "740c210d", "C14": "1adce6ef", "C15": "310d155b", "C16": "07eb8110", "C17": "07c540c4", "C18": "891589e7", "C19": "18259a83", "C2": "287130e0", "C20": "a458ea53", "C21": "a0ab60ca", "C22": "0", "C23": "32c7478e", "C24": "a052b1ed", "C25": "9b3e8820", "C26": "8967c0d2", "C3": "cd7a7a22", "C4": "fb7334df", "C5": "25c83c98", "C6": "0", "C7": "6cdb3998", "C8": "361384ce", "C9": "a73ee510", "I1": 0, "I10": 0, "I11": 1, "I12": 0, "I13": 5, "I2": 2, "I3": 11, "I4": 5, "I5": 10262, "I6": 34, "I7": 2, "I8": 4, "I9": 5 } 2 | -------------------------------------------------------------------------------- /trainer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yufengg/widendeep/cfbd177779f08484813a870a11a646b63efdff79/trainer/__init__.py -------------------------------------------------------------------------------- /trainer/model.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from __future__ import division 3 | from __future__ import print_function 4 | 5 | import time 6 | 7 | import tensorflow as tf 8 | #from tensorflow.contrib.learn.python.learn import learn_runner 9 | from tensorflow.contrib.learn.python.learn.utils import input_fn_utils 10 | #from tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils 11 | 12 | 13 | tf.logging.set_verbosity(tf.logging.ERROR) 14 | 15 | CONTINUOUS_COLUMNS = ["I"+str(i) for i in range(1,14)] # 1-13 inclusive 16 | CATEGORICAL_COLUMNS = ["C"+str(i) for i in range(1,27)] # 1-26 inclusive 17 | LABEL_COLUMN = ["clicked"] 18 | 19 | TRAIN_DATA_COLUMNS = LABEL_COLUMN + CONTINUOUS_COLUMNS + CATEGORICAL_COLUMNS 20 | # TEST_DATA_COLUMNS = CONTINUOUS_COLUMNS + CATEGORICAL_COLUMNS 21 | 22 | FEATURE_COLUMNS = CONTINUOUS_COLUMNS + CATEGORICAL_COLUMNS 23 | 24 | def generate_input_fn(filename): 25 | def _input_fn(): 26 | BATCH_SIZE = 40 27 | filename_queue = tf.train.string_input_producer([filename]) 28 | reader = tf.TextLineReader() 29 | key, value = reader.read_up_to(filename_queue, num_records=BATCH_SIZE) 30 | 31 | # 1 int label, 13 ints, 26 strings 32 | cont_defaults = [ [0] for i in range(1,14) ] 33 | cate_defaults = [ [0] for i in range(1,27) ] 34 | label_defaults = [ [0] ] 35 | column_headers = TRAIN_DATA_COLUMNS 36 | record_defaults = [ label_defaults + cont_defaults + cate_defaults ] 37 | 38 | columns = tf.decode_csv( 39 | value, record_defaults=record_defaults, field_delim='\t') 40 | 41 | features = dict(zip(column_headers, columns)) 42 | 43 | # save our label 44 | labels = features.pop(LABEL_COLUMN) 45 | 46 | for feature_name in CATEGORICAL_COLUMNS: 47 | features[feature_name] = tf.expand_dims(features[feature_name], -1) 48 | 49 | return features, labels 50 | 51 | return _input_fn 52 | 53 | -------------------------------------------------------------------------------- /trainer/task.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache 2 | # License, Version 2.0 (the "License"); you may not use this file except in 3 | # compliance with the License. You may obtain a copy of the License at 4 | # http://www.apache.org/licenses/LICENSE-2.0 5 | 6 | # Unless required by applicable law or agreed to in writing, software 7 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 8 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 9 | # License for the specific language governing permissions and limitations under 10 | # the License. 11 | 12 | from __future__ import absolute_import 13 | from __future__ import division 14 | from __future__ import print_function 15 | 16 | import time 17 | import argparse 18 | 19 | import tensorflow as tf 20 | from tensorflow.contrib.learn.python.learn import learn_runner 21 | from tensorflow.contrib.learn.python.learn.datasets import base 22 | from tensorflow.contrib.learn.python.learn.utils import input_fn_utils 23 | from tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils 24 | 25 | 26 | tf.logging.set_verbosity(tf.logging.INFO) # Set to INFO for tracking training, default is WARN. ERROR for least messages 27 | 28 | print("Using TensorFlow version %s" % (tf.__version__)) 29 | 30 | CONTINUOUS_COLUMNS = ["I"+str(i) for i in range(1,14)] # 1-13 inclusive 31 | CATEGORICAL_COLUMNS = ["C"+str(i) for i in range(1,27)] # 1-26 inclusive 32 | LABEL_COLUMN = ["clicked"] 33 | 34 | TRAIN_DATA_COLUMNS = LABEL_COLUMN + CONTINUOUS_COLUMNS + CATEGORICAL_COLUMNS 35 | 36 | FEATURE_COLUMNS = CONTINUOUS_COLUMNS + CATEGORICAL_COLUMNS 37 | 38 | BATCH_SIZE = 40 39 | 40 | def generate_input_fn(filename, batch_size=BATCH_SIZE): 41 | def _input_fn(): 42 | filename_queue = tf.train.string_input_producer([filename]) 43 | reader = tf.TextLineReader() 44 | # Reads out batch_size number of lines 45 | key, value = reader.read_up_to(filename_queue, num_records=batch_size) 46 | 47 | # 1 int label, 13 ints, 26 strings 48 | cont_defaults = [ [0] for i in range(1,14) ] 49 | cate_defaults = [ [" "] for i in range(1,27) ] 50 | label_defaults = [ [0] ] 51 | column_headers = TRAIN_DATA_COLUMNS 52 | record_defaults = label_defaults + cont_defaults + cate_defaults 53 | 54 | # Decode CSV data that was just read out. 55 | columns = tf.decode_csv( 56 | value, record_defaults=record_defaults) 57 | 58 | # features is a dictionary that maps from column names to tensors of the data. 59 | # income_bracket is the last column of the data. Note that this is NOT a dict. 60 | all_columns = dict(zip(column_headers, columns)) 61 | 62 | # Save the label column 63 | # dict.pop() returns the popped array of label values 64 | labels = all_columns.pop(LABEL_COLUMN[0]) 65 | 66 | # the remaining columns are our features 67 | features = all_columns 68 | 69 | # Sparse categorical features must be represented with an additional dimension. 70 | # There is no additional work needed for the Continuous columns; they are the unaltered columns. 71 | # See docs for tf.SparseTensor for more info 72 | for feature_name in CATEGORICAL_COLUMNS: 73 | features[feature_name] = tf.expand_dims(features[feature_name], -1) 74 | 75 | return features, labels 76 | 77 | return _input_fn 78 | 79 | 80 | def build_feature_cols(): 81 | # Sparse base columns. 82 | wide_columns = [] 83 | for name in CATEGORICAL_COLUMNS: 84 | wide_columns.append(tf.contrib.layers.sparse_column_with_hash_bucket(name, hash_bucket_size=1000)) 85 | 86 | # Continuous base columns. 87 | deep_columns = [] 88 | for name in CONTINUOUS_COLUMNS: 89 | deep_columns.append(tf.contrib.layers.real_valued_column(name)) 90 | 91 | # No transformations. 92 | # Embed wide columns into deep columns 93 | for col in wide_columns: 94 | deep_columns.append(tf.contrib.layers.embedding_column(col, dimension=8)) 95 | 96 | return wide_columns, deep_columns 97 | 98 | def build_model(model_type, model_dir, wide_columns, deep_columns): 99 | runconfig = tf.contrib.learn.RunConfig( 100 | save_checkpoints_secs=120, 101 | save_checkpoints_steps = None, 102 | gpu_memory_fraction = 0.8 103 | ) 104 | m = None 105 | # Linear Classifier 106 | if model_type == 'WIDE': 107 | m = tf.contrib.learn.LinearClassifier( 108 | config=runconfig, 109 | model_dir=model_dir, 110 | feature_columns=wide_columns) 111 | 112 | # Deep Neural Net Classifier 113 | elif model_type == 'DEEP': 114 | m = tf.contrib.learn.DNNClassifier( 115 | config=runconfig, 116 | model_dir=model_dir, 117 | feature_columns=deep_columns, 118 | hidden_units=[100, 70, 50, 25]) 119 | 120 | # Combined Linear and Deep Classifier 121 | elif model_type == 'WIDE_AND_DEEP': 122 | m = tf.contrib.learn.DNNLinearCombinedClassifier( 123 | config=runconfig, 124 | model_dir=model_dir, 125 | linear_feature_columns=wide_columns, 126 | dnn_feature_columns=deep_columns, 127 | dnn_hidden_units=[100, 70, 50, 25]) 128 | 129 | return m 130 | 131 | 132 | def build_estimator(model_type='WIDE_AND_DEEP', model_dir=None): 133 | if model_dir is None: 134 | model_dir = 'models/model_' + model_type + '_' + str(int(time.time())) 135 | print("Model directory = %s" % model_dir) 136 | 137 | wide_columns, deep_columns = build_feature_cols() 138 | m = build_model(model_type, model_dir, wide_columns, deep_columns) 139 | print('estimator built') 140 | return m 141 | 142 | 143 | # All categorical columns are strings for this dataset 144 | def column_to_dtype(column): 145 | if column in CATEGORICAL_COLUMNS: 146 | return tf.string 147 | else: 148 | return tf.float32 149 | 150 | """ 151 | This function maps input columns (feature_placeholders) to 152 | tensors that can be inputted into the graph 153 | (similar in purpose to the output of our input functions) 154 | In this particular case, we need to accomodate the sparse fields (strings) 155 | so we have to do a slight modification to expand their dimensions, 156 | just like in the input functions 157 | """ 158 | def serving_input_fn(): 159 | feature_placeholders = { 160 | column: tf.placeholder(column_to_dtype(column), [None]) 161 | for column in FEATURE_COLUMNS 162 | } 163 | # DNNCombinedLinearClassifier expects rank 2 Tensors, 164 | # but inputs should be rank 1, so that we can provide 165 | # scalars to the server 166 | features = { 167 | key: tf.expand_dims(tensor, -1) 168 | for key, tensor in feature_placeholders.items() 169 | } 170 | 171 | return input_fn_utils.InputFnOps( 172 | features, # input into graph 173 | None, 174 | feature_placeholders # tensor input converted from request 175 | ) 176 | 177 | def generate_experiment(output_dir, train_file, test_file, model_type): 178 | def _experiment_fn(output_dir): 179 | batch_size = 40 # make it larger for large datasets: 40, 400, 4000 180 | train_input_fn = generate_input_fn(train_file, batch_size) 181 | eval_input_fn = generate_input_fn(test_file, batch_size) 182 | my_model = build_estimator(model_type=model_type, 183 | model_dir=output_dir) 184 | 185 | experiment = tf.contrib.learn.Experiment( 186 | my_model, 187 | train_input_fn=train_input_fn, 188 | eval_input_fn=eval_input_fn, 189 | train_steps=1000 190 | , 191 | export_strategies=[saved_model_export_utils.make_export_strategy( 192 | serving_input_fn, 193 | default_output_alternative_key=None 194 | )] 195 | ) 196 | return experiment 197 | 198 | return _experiment_fn 199 | 200 | 201 | def train_and_eval(job_dir=None): 202 | print("Begin training and evaluation") 203 | 204 | # if local eval and no args passed, default 205 | if job_dir is None: job_dir = 'models/' 206 | 207 | # Ensure path has a '/' at the end 208 | if job_dir[-1] != '/': job_dir += '/' 209 | 210 | gcs_base = 'https://storage.googleapis.com/' # No need to change 211 | # small_version, medium_version, large_version 212 | # Note: large_version is 2.7GB and medium_version is 273MB 213 | gcs_path = 'dataset-uploader/criteo-kaggle/small_version/' # Path to the folder with the files 214 | trainfile = 'train.csv' 215 | testfile = 'eval.csv' 216 | local_path = 'dataset_files' 217 | train_file = base.maybe_download( 218 | trainfile, local_path, gcs_base + gcs_path + trainfile) 219 | test_file = base.maybe_download( 220 | testfile, local_path, gcs_base + gcs_path + testfile) 221 | 222 | training_mode = 'learn_runner' 223 | train_steps = 1000 224 | test_steps = 100 225 | model_type = 'DEEP' 226 | 227 | model_dir = job_dir + 'model_' + model_type + '_' + str(int(time.time())) 228 | print("Saving model checkpoints to " + model_dir) 229 | export_dir = model_dir + '/exports' 230 | 231 | # Manually train and export model 232 | if training_mode == 'manual': 233 | # In this function, editing below here is unlikely to be needed 234 | m = build_estimator(model_type, model_dir) 235 | 236 | m.fit(input_fn=generate_input_fn(train_file), steps=train_steps) 237 | print('fit done') 238 | 239 | results = m.evaluate(input_fn=generate_input_fn(test_file), steps=test_steps) 240 | print('evaluate done') 241 | 242 | print('Accuracy: %s' % results['accuracy']) 243 | 244 | export_folder = m.export_savedmodel( 245 | export_dir_base = export_dir, 246 | input_fn=serving_input_fn 247 | ) 248 | 249 | print('Model exported to ' + export_dir) 250 | 251 | elif training_mode == 'learn_runner': 252 | # use learn_runner 253 | experiment_fn = generate_experiment( 254 | model_dir, train_file, test_file, model_type) 255 | 256 | learn_runner.run(experiment_fn, model_dir) 257 | 258 | 259 | def version_is_less_than(a, b): 260 | a_parts = a.split('.') 261 | b_parts = b.split('.') 262 | 263 | for i in range(len(a_parts)): 264 | if int(a_parts[i]) < int(b_parts[i]): 265 | print('{} < {}, version_is_less_than() returning False'.format( 266 | a_parts[i], b_parts[i])) 267 | return True 268 | return False 269 | 270 | def get_arg_parser(): 271 | parser = argparse.ArgumentParser() 272 | 273 | parser.add_argument( 274 | '--job-dir', 275 | help='GCS location to write checkpoints and export models', 276 | required=False 277 | ) 278 | 279 | return parser 280 | 281 | if __name__ == "__main__": 282 | print("TensorFlow version {}".format(tf.__version__)) 283 | required_tf_version = '1.0.0' 284 | if version_is_less_than(tf.__version__ , required_tf_version): 285 | raise ValueError('This code requires tensorflow >= ' + str(required_tf_version)) 286 | 287 | parser = get_arg_parser() 288 | args = parser.parse_args() 289 | train_and_eval(args.job_dir) 290 | -------------------------------------------------------------------------------- /wnd_criteo.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Wide and Deep on TensorFlow (notebook style)" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Copyright 2016 Google Inc. 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\n", 15 | " http://www.apache.org/licenses/LICENSE-2.0\n", 16 | "\n", 17 | "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." 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "metadata": {}, 23 | "source": [ 24 | "# Introduction\n", 25 | "\n", 26 | "This notebook uses the tf.learn API in TensorFlow to answer a yes/no question. This is called a binary classification problem: Given census data about a person such as age, gender, education and occupation (the features), we will try to predict whether or not the person earns more than 50,000 dollars a year (the target label). \n", 27 | "\n", 28 | "Given an individual's information our model will output a number between 0 and 1, which can be interpreted as the model's certainty that the individual has an annual income of over 50,000 dollars, (1=True, 0=False)\n" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": {}, 34 | "source": [ 35 | "# Imports and constants\n", 36 | "First we'll import our libraries and set up some strings for column names. We also print out the version of TensorFlow we are running." 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": null, 42 | "metadata": { 43 | "collapsed": false 44 | }, 45 | "outputs": [], 46 | "source": [ 47 | "from __future__ import absolute_import\n", 48 | "from __future__ import division\n", 49 | "from __future__ import print_function\n", 50 | "\n", 51 | "import time\n", 52 | "\n", 53 | "import tensorflow as tf\n", 54 | "\n", 55 | "tf.logging.set_verbosity(tf.logging.INFO) # Set to INFO for tracking training, default is WARN. ERROR for least messages\n", 56 | "\n", 57 | "print(\"Using TensorFlow version %s\\n\" % (tf.__version__))\n", 58 | "\n", 59 | "\n", 60 | "CONTINUOUS_COLUMNS = [\"I\"+str(i) for i in range(1,14)] # 1-13 inclusive\n", 61 | "CATEGORICAL_COLUMNS = [\"C\"+str(i) for i in range(1,27)] # 1-26 inclusive\n", 62 | "LABEL_COLUMN = [\"clicked\"]\n", 63 | "\n", 64 | "TRAIN_DATA_COLUMNS = LABEL_COLUMN + CONTINUOUS_COLUMNS + CATEGORICAL_COLUMNS\n", 65 | "# TEST_DATA_COLUMNS = CONTINUOUS_COLUMNS + CATEGORICAL_COLUMNS\n", 66 | "\n", 67 | "FEATURE_COLUMNS = CONTINUOUS_COLUMNS + CATEGORICAL_COLUMNS\n", 68 | "\n", 69 | "print('Feature columns are: ', FEATURE_COLUMNS, '\\n')\n", 70 | "\n", 71 | " # label is 1\n", 72 | "sample = [ 0 , 2, 11, 5, 10262, 34, 2, 4, 5,0 , 1,0 , 5, \"be589b51\", \"287130e0\", \"cd7a7a22\", \"fb7334df\", \"25c83c98\",\"0\" , \"6cdb3998\", \"361384ce\", \"a73ee510\", \"3ff10fb2\", \"5874c9c9\", \"976cbd4c\", \"740c210d\", \"1adce6ef\", \"310d155b\", \"07eb8110\", \"07c540c4\", \"891589e7\", \"18259a83\", \"a458ea53\", \"a0ab60ca\",\"0\" , \"32c7478e\", \"a052b1ed\", \"9b3e8820\", \"8967c0d2\"]\n", 73 | "\n", 74 | "# label is 1\n", 75 | "sample = [ 0, 127, 1, 3, 1683, 19, 26, 17, 475, 0, 9, 0, 3, \"05db9164\", \"8947f767\", \"11c9d79e\", \"52a787c8\", \"4cf72387\", \"fbad5c96\", \"18671b18\", \"0b153874\", \"a73ee510\", \"ceb10289\", \"77212bd7\", \"79507c6b\", \"7203f04e\", \"07d13a8f\", \"2c14c412\", \"49013ffe\", \"8efede7f\", \"bd17c3da\", \"f6a3e43b\", \"a458ea53\", \"35cd95c9\", \"ad3062eb\", \"c7dc6720\", \"3fdb382b\", \"010f6491\", \"49d68486\"]\n", 76 | "\n", 77 | "print('Columns and data as a dict: ', dict(zip(FEATURE_COLUMNS, sample)), '\\n')" 78 | ] 79 | }, 80 | { 81 | "cell_type": "markdown", 82 | "metadata": {}, 83 | "source": [ 84 | "# Input file parsing\n", 85 | "\n", 86 | "This section puts the file into a `Reader` which reads from the file one batch at a time. \n", 87 | "\n", 88 | "We set up the Tensors to be a dictionary of features mapping from their string name to the tensor value.\n", 89 | "\n", 90 | "Note that the `_input_fn()` function is wrapped, enabling it to be used for different files.\n", 91 | "\n", 92 | "NOTE: This reads from the input file directly via TensorFlow, rather than using an intermediate tool such as pandas to load the entire dataset into memory first. This is done to enable the system to scale to large inputs." 93 | ] 94 | }, 95 | { 96 | "cell_type": "markdown", 97 | "metadata": {}, 98 | "source": [ 99 | "## More about input functions\n", 100 | "\n", 101 | "The input function is how we will feed the input data into the model during training and evaluation. \n", 102 | "The structure that must be returned is a pair, where the first element is a dict of the column names (features) mapped to a tensor of values, and the 2nd element is a tensor of values representing the answers (labels). Recall that a tensor is just a general term for an n-dimensional array.\n", 103 | "\n", 104 | "This could be represented as: `map(column_name => [Tensor of values]) , [Tensor of labels])`\n", 105 | "\n", 106 | "More concretely, for this particular dataset, something like this:\n", 107 | "\n", 108 | " { \n", 109 | " 'age': [ 39, 50, 38, 53, 28, … ], \n", 110 | " 'marital_status': [ 'Married-civ-spouse', 'Never-married', 'Widowed', 'Widowed' … ],\n", 111 | " ...\n", 112 | " 'gender': ['Male', 'Female', 'Male', 'Male', 'Female',, … ], \n", 113 | " } , \n", 114 | " [ 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1]\n", 115 | " \n", 116 | "Additionally, we define which columns of the input data we will treat as categorical vs continuous, using the global `CATEGORICAL_COLUMNS`.\n", 117 | "\n", 118 | "You can try different values for `BATCH_SIZE` to see how they impact your results" 119 | ] 120 | }, 121 | { 122 | "cell_type": "markdown", 123 | "metadata": {}, 124 | "source": [ 125 | "### High-level structure of input functions for CSV-style data\n", 126 | "1. Queue file(s)\n", 127 | "2. Read a batch of data from the next file\n", 128 | "3. Create record defaults, generally 0 for continuous values, and \"\" for categorical. You can use named types if you prefer\n", 129 | "4. Decode the CSV and restructure it to be appropriate for the graph's input format\n", 130 | " * `zip()` column headers with the data\n", 131 | " * `pop()` off the label column(s)\n", 132 | " * Remove/pop any unneeded column(s)\n", 133 | " * Run `tf.expand_dims()` on categorical columns\n", 134 | " 5. Return the pair: `(feature_dict, label_array)`\n", 135 | " " 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "execution_count": null, 141 | "metadata": { 142 | "collapsed": false 143 | }, 144 | "outputs": [], 145 | "source": [ 146 | "BATCH_SIZE = 400\n", 147 | "\n", 148 | "def generate_input_fn(filename, batch_size=BATCH_SIZE):\n", 149 | " def _input_fn():\n", 150 | " filename_queue = tf.train.string_input_producer([filename])\n", 151 | " reader = tf.TextLineReader()\n", 152 | " # Reads out batch_size number of lines\n", 153 | " key, value = reader.read_up_to(filename_queue, num_records=batch_size)\n", 154 | " \n", 155 | " # 1 int label, 13 ints, 26 strings\n", 156 | " cont_defaults = [ [0] for i in range(1,14) ]\n", 157 | " cate_defaults = [ [\" \"] for i in range(1,27) ]\n", 158 | " label_defaults = [ [0] ]\n", 159 | " column_headers = TRAIN_DATA_COLUMNS\n", 160 | " # The label is the first column of the data.\n", 161 | " record_defaults = label_defaults + cont_defaults + cate_defaults\n", 162 | "\n", 163 | " # Decode CSV data that was just read out. \n", 164 | " # Note that this does NOT return a dict, \n", 165 | " # so we will need to zip it up with our headers\n", 166 | " columns = tf.decode_csv(\n", 167 | " value, record_defaults=record_defaults)\n", 168 | " \n", 169 | " # all_columns is a dictionary that maps from column names to tensors of the data.\n", 170 | " all_columns = dict(zip(column_headers, columns))\n", 171 | " \n", 172 | " # Pop and save our labels \n", 173 | " # dict.pop() returns the popped array of values; exactly what we need!\n", 174 | " labels = all_columns.pop(LABEL_COLUMN[0])\n", 175 | " \n", 176 | " # the remaining columns are our features\n", 177 | " features = all_columns \n", 178 | "\n", 179 | " # Sparse categorical features must be represented with an additional dimension. \n", 180 | " # There is no additional work needed for the Continuous columns; they are the unaltered columns.\n", 181 | " # See docs for tf.SparseTensor for more info\n", 182 | " for feature_name in CATEGORICAL_COLUMNS:\n", 183 | " features[feature_name] = tf.expand_dims(features[feature_name], -1)\n", 184 | "\n", 185 | " return features, labels\n", 186 | "\n", 187 | " return _input_fn\n", 188 | "\n", 189 | "print('input function configured')" 190 | ] 191 | }, 192 | { 193 | "cell_type": "markdown", 194 | "metadata": {}, 195 | "source": [ 196 | "# Create Feature Columns\n", 197 | "This section configures the model with the information about the model. There are many parameters here to experiment with to see how they affect the accuracy.\n", 198 | "\n", 199 | "This is the bulk of the time and energy that is often spent on making a machine learning model work, called *feature selection* or *feature engineering*. We choose the features (columns) we will use for training, and apply any additional transformations to them as needed. " 200 | ] 201 | }, 202 | { 203 | "cell_type": "markdown", 204 | "metadata": {}, 205 | "source": [ 206 | "### Sparse Columns\n", 207 | "First we build the sparse columns.\n", 208 | "\n", 209 | "Use `sparse_column_with_keys()` for columns that we know all possible values for.\n", 210 | "\n", 211 | "Use `sparse_column_with_hash_bucket()` for columns that we want the the library to automatically map values for us." 212 | ] 213 | }, 214 | { 215 | "cell_type": "code", 216 | "execution_count": null, 217 | "metadata": { 218 | "collapsed": false, 219 | "scrolled": true 220 | }, 221 | "outputs": [], 222 | "source": [ 223 | "# Sparse base columns.\n", 224 | "# C1 = tf.contrib.layers.sparse_column_with_hash_bucket('C1', hash_bucket_size=1000)\n", 225 | "# C2 = tf.contrib.layers.sparse_column_with_hash_bucket('C2', hash_bucket_size=1000)\n", 226 | "# C3 = tf.contrib.layers.sparse_column_with_hash_bucket('C3', hash_bucket_size=1000)\n", 227 | "# ...\n", 228 | "# Cn = tf.contrib.layers.sparse_column_with_hash_bucket('Cn', hash_bucket_size=1000)\n", 229 | "# wide_columns = [C1, C2, C3, ... , Cn]\n", 230 | "\n", 231 | "wide_columns = []\n", 232 | "for name in CATEGORICAL_COLUMNS:\n", 233 | " wide_columns.append(tf.contrib.layers.sparse_column_with_hash_bucket(\n", 234 | " name, hash_bucket_size=1000))\n", 235 | "\n", 236 | "print('Wide/Sparse columns configured')" 237 | ] 238 | }, 239 | { 240 | "cell_type": "markdown", 241 | "metadata": {}, 242 | "source": [ 243 | "### Continuous columns\n", 244 | "Second, configure the real-valued columns using `real_valued_column()`. " 245 | ] 246 | }, 247 | { 248 | "cell_type": "code", 249 | "execution_count": null, 250 | "metadata": { 251 | "collapsed": false 252 | }, 253 | "outputs": [], 254 | "source": [ 255 | "# Continuous base columns.\n", 256 | "# I1 = tf.contrib.layers.real_valued_column(\"I1\")\n", 257 | "# I2 = tf.contrib.layers.real_valued_column(\"I2\")\n", 258 | "# I3 = tf.contrib.layers.real_valued_column(\"I3\")\n", 259 | "# ...\n", 260 | "# In = tf.contrib.layers.real_valued_column(\"In\")\n", 261 | "# deep_columns = [I1, I2, I3, ... , In]\n", 262 | "\n", 263 | "deep_columns = []\n", 264 | "for name in CONTINUOUS_COLUMNS:\n", 265 | " deep_columns.append(tf.contrib.layers.real_valued_column(name))\n", 266 | "\n", 267 | "print('deep/continuous columns configured')" 268 | ] 269 | }, 270 | { 271 | "cell_type": "markdown", 272 | "metadata": {}, 273 | "source": [ 274 | "### Transformations\n", 275 | "Now for the interesting stuff. We will employ a couple of techniques to get even more out of the data.\n", 276 | " \n", 277 | "* **bucketizing** turns what would have otherwise been a continuous feature into a categorical one. \n", 278 | "* **feature crossing** allows us to compute a model weight for specific pairings across columns, rather than learning them as independently. This essentially encodes related columns together, for situations where having 2 (or more) columns being certain values is meaningful. \n", 279 | "\n", 280 | "Only categorical features can be crossed. This is one reason why age has been bucketized.\n", 281 | "\n", 282 | "For example, crossing education and occupation would enable the model to learn about: \n", 283 | "\n", 284 | " education=\"Bachelors\" AND occupation=\"Exec-managerial\"\n", 285 | "\n", 286 | "or perhaps \n", 287 | "\n", 288 | " education=\"Bachelors\" AND occupation=\"Craft-repair\"\n", 289 | "\n", 290 | "We do a few combined features (feature crosses) here. \n", 291 | "\n", 292 | "Add your own, based on your intuitions about the dataset, to try to improve on the model!" 293 | ] 294 | }, 295 | { 296 | "cell_type": "code", 297 | "execution_count": null, 298 | "metadata": { 299 | "collapsed": false 300 | }, 301 | "outputs": [], 302 | "source": [ 303 | "# No known Transformations. Can add some if desired. \n", 304 | "# Examples from other datasets are shown below.\n", 305 | "\n", 306 | "# age_buckets = tf.contrib.layers.bucketized_column(age,\n", 307 | "# boundaries=[ 18, 25, 30, 35, 40, 45, 50, 55, 60, 65 ])\n", 308 | "# education_occupation = tf.contrib.layers.crossed_column([education, occupation], \n", 309 | "# hash_bucket_size=int(1e4))\n", 310 | "# age_race_occupation = tf.contrib.layers.crossed_column([age_buckets, race, occupation], \n", 311 | "# hash_bucket_size=int(1e6))\n", 312 | "# country_occupation = tf.contrib.layers.crossed_column([native_country, occupation], \n", 313 | "# hash_bucket_size=int(1e4))\n", 314 | "\n", 315 | "print('Transformations complete')" 316 | ] 317 | }, 318 | { 319 | "cell_type": "markdown", 320 | "metadata": {}, 321 | "source": [ 322 | "### Group feature columns into 2 objects\n", 323 | "\n", 324 | "The wide columns are the sparse, categorical columns that we specified, as well as our hashed, bucket, and feature crossed columns. \n", 325 | "\n", 326 | "The deep columns are composed of embedded categorical columns along with the continuous real-valued columns. **Column embeddings** transform a sparse, categorical tensor into a low-dimensional and dense real-valued vector. The embedding values are also trained along with the rest of the model. For more information about embeddings, see the TensorFlow tutorial on [Vector Representations Words](https://www.tensorflow.org/tutorials/word2vec/), or [Word Embedding](https://en.wikipedia.org/wiki/Word_embedding) on Wikipedia.\n", 327 | "\n", 328 | "The higher the dimension of the embedding is, the more degrees of freedom the model will have to learn the representations of the features. We are starting with an 8-dimension embedding for simplicity, but later you can come back and increase the dimensionality if you wish.\n", 329 | "\n" 330 | ] 331 | }, 332 | { 333 | "cell_type": "code", 334 | "execution_count": null, 335 | "metadata": { 336 | "collapsed": false, 337 | "scrolled": true 338 | }, 339 | "outputs": [], 340 | "source": [ 341 | "# Wide columns and deep columns.\n", 342 | "# wide_columns = [gender, race, native_country,\n", 343 | "# education, occupation, workclass,\n", 344 | "# marital_status, relationship,\n", 345 | "# age_buckets, education_occupation,\n", 346 | "# age_race_occupation, country_occupation]\n", 347 | "\n", 348 | "# deep_columns = [\n", 349 | "# tf.contrib.layers.embedding_column(workclass, dimension=8),\n", 350 | "# tf.contrib.layers.embedding_column(education, dimension=8),\n", 351 | "# tf.contrib.layers.embedding_column(marital_status, dimension=8),\n", 352 | "# tf.contrib.layers.embedding_column(gender, dimension=8),\n", 353 | "# tf.contrib.layers.embedding_column(relationship, dimension=8),\n", 354 | "# tf.contrib.layers.embedding_column(race, dimension=8),\n", 355 | "# tf.contrib.layers.embedding_column(native_country, dimension=8),\n", 356 | "# tf.contrib.layers.embedding_column(occupation, dimension=8),\n", 357 | "# age,\n", 358 | "# education_num,\n", 359 | "# capital_gain,\n", 360 | "# capital_loss,\n", 361 | "# hours_per_week,\n", 362 | "# ]\n", 363 | "\n", 364 | "# Embeddings for wide columns into deep columns\n", 365 | "for col in wide_columns:\n", 366 | " deep_columns.append(tf.contrib.layers.embedding_column(col, \n", 367 | " dimension=8))\n", 368 | "\n", 369 | "print('wide and deep columns configured')" 370 | ] 371 | }, 372 | { 373 | "cell_type": "markdown", 374 | "metadata": {}, 375 | "source": [ 376 | "# Create the model\n", 377 | "\n", 378 | "You can train either a \"wide\" model, a \"deep\" model, or a \"wide and deep\" model, using the classifiers below. Try each one and see what kind of results you get.\n", 379 | "\n", 380 | "* **Wide**: Linear Classifier\n", 381 | "* **Deep**: Deep Neural Net Classifier\n", 382 | "* **Wide & Deep**: Combined Linear and Deep Classifier\n", 383 | "\n", 384 | "The `hidden_units` or `dnn_hidden_units` argument is to specify the size of each layer of the deep portion of the network. For example, `[12, 20, 15]` would create a network with the first layer of size 12, the second layer of size 20, and a third layer of size 15." 385 | ] 386 | }, 387 | { 388 | "cell_type": "code", 389 | "execution_count": null, 390 | "metadata": { 391 | "collapsed": false 392 | }, 393 | "outputs": [], 394 | "source": [ 395 | "def create_model_dir(model_type):\n", 396 | " # Returns something like models/model_WIDE_AND_DEEP_1493043407\n", 397 | " return 'models/model_' + model_type + '_' + str(int(time.time()))\n", 398 | "\n", 399 | "# Specify the desired model_dir \n", 400 | "def get_model(model_type, model_dir):\n", 401 | " print(\"Model directory = %s\" % model_dir)\n", 402 | " \n", 403 | " # There are more options here than shown here. \n", 404 | " # We are using this to show additional checkpointing for illustrative purposes.\n", 405 | " # In a real system with far more samples, you would \n", 406 | " # likely choose to save checkpoints less frequently.\n", 407 | " runconfig = tf.contrib.learn.RunConfig(\n", 408 | " save_checkpoints_secs=None,\n", 409 | " save_checkpoints_steps = 100,\n", 410 | " )\n", 411 | " \n", 412 | " m = None\n", 413 | " \n", 414 | " # Linear Classifier\n", 415 | " if model_type == 'WIDE':\n", 416 | " m = tf.contrib.learn.LinearClassifier(\n", 417 | " model_dir=model_dir, \n", 418 | " feature_columns=wide_columns)\n", 419 | "\n", 420 | " # Deep Neural Net Classifier\n", 421 | " if model_type == 'DEEP':\n", 422 | " m = tf.contrib.learn.DNNClassifier(\n", 423 | " model_dir=model_dir,\n", 424 | " feature_columns=deep_columns,\n", 425 | " hidden_units=[100, 50, 25])\n", 426 | "\n", 427 | " # Combined Linear and Deep Classifier\n", 428 | " if model_type == 'WIDE_AND_DEEP':\n", 429 | " m = tf.contrib.learn.DNNLinearCombinedClassifier(\n", 430 | " model_dir=model_dir,\n", 431 | " linear_feature_columns=wide_columns,\n", 432 | " dnn_feature_columns=deep_columns,\n", 433 | " dnn_hidden_units=[100, 70, 50, 25],\n", 434 | " config=runconfig)\n", 435 | " \n", 436 | " print('estimator built')\n", 437 | " \n", 438 | " return m\n", 439 | " \n", 440 | "\n", 441 | "MODEL_TYPE = 'WIDE_AND_DEEP'\n", 442 | "model_dir = create_model_dir(model_type=MODEL_TYPE)\n", 443 | "m = get_model(model_type=MODEL_TYPE, model_dir=model_dir)" 444 | ] 445 | }, 446 | { 447 | "cell_type": "code", 448 | "execution_count": null, 449 | "metadata": { 450 | "collapsed": false 451 | }, 452 | "outputs": [], 453 | "source": [ 454 | "# Showing that canned estimators return an instance of 'Evaluable'\n", 455 | "\n", 456 | "from tensorflow.contrib.learn.python.learn import evaluable\n", 457 | "isinstance(m, evaluable.Evaluable)\n" 458 | ] 459 | }, 460 | { 461 | "cell_type": "markdown", 462 | "metadata": {}, 463 | "source": [ 464 | "# Fit the model (train it)\n", 465 | "\n", 466 | "Run `fit()` to train the model. You can experiment with the `train_steps` and `BATCH_SIZE` parameters.\n", 467 | "\n", 468 | "This can take some time, depending on the values chosen for `train_steps` and `BATCH_SIZE`.\n", 469 | "\n", 470 | "Our datafile is hosted on Google Cloud Storage; the reader we created at the beginning knows how to read from it.\n", 471 | "\n", 472 | "If you don't want to download a new copy of the dataset each time your script runs, you can download it locally using \n", 473 | "\n", 474 | " gsutil cp gs://dataset-uploader/criteo-kaggle/medium_version/train.csv .\n", 475 | " gsutil cp gs://dataset-uploader/criteo-kaggle/medium_version/eval.csv .\n", 476 | " \n", 477 | "If you want to download it manually, use\n", 478 | "\n", 479 | "- http://storageapis.google.com/dataset-uploader/criteo-kaggle/medium_version/eval.csv\n", 480 | "- http://storageapis.google.com/dataset-uploader/criteo-kaggle/medium_version/train.csv" 481 | ] 482 | }, 483 | { 484 | "cell_type": "code", 485 | "execution_count": null, 486 | "metadata": { 487 | "collapsed": true 488 | }, 489 | "outputs": [], 490 | "source": [ 491 | "# Use the cloud or local depending on your preference\n", 492 | "\n", 493 | "# CLOUD\n", 494 | "train_file = \"gs://dataset-uploader/criteo-kaggle/medium_version/train.csv\"\n", 495 | "eval_file = \"gs://dataset-uploader/criteo-kaggle/medium_version/eval.csv\"\n", 496 | "\n", 497 | "# LOCAL. Update these paths as appropriate\n", 498 | "train_file = \"data_files/medium_version/train.csv\"\n", 499 | "eval_file = \"data_files/medium_version/eval.csv\"\n" 500 | ] 501 | }, 502 | { 503 | "cell_type": "code", 504 | "execution_count": null, 505 | "metadata": { 506 | "collapsed": false, 507 | "scrolled": true 508 | }, 509 | "outputs": [], 510 | "source": [ 511 | "%%time\n", 512 | "\n", 513 | "# This can be found with\n", 514 | "# wc -l train.csv\n", 515 | "train_sample_size = 800000\n", 516 | "train_steps = train_sample_size/BATCH_SIZE # 8000/40 = 200\n", 517 | "\n", 518 | "m.fit(input_fn=generate_input_fn(train_file, BATCH_SIZE), steps=train_steps)\n", 519 | "\n", 520 | "print('fit done')" 521 | ] 522 | }, 523 | { 524 | "cell_type": "markdown", 525 | "metadata": {}, 526 | "source": [ 527 | "# Evaluate the accuracy of the model\n", 528 | "Let's see how the model did. We will evaluate all the test data." 529 | ] 530 | }, 531 | { 532 | "cell_type": "code", 533 | "execution_count": null, 534 | "metadata": { 535 | "collapsed": false, 536 | "scrolled": true 537 | }, 538 | "outputs": [], 539 | "source": [ 540 | "%%time\n", 541 | "\n", 542 | "eval_sample_size = 200000 # this can be found with a 'wc -l eval.csv'\n", 543 | "eval_steps = eval_sample_size/BATCH_SIZE # 2000/40 = 50\n", 544 | "\n", 545 | "results = m.evaluate(input_fn=generate_input_fn(eval_file), \n", 546 | " steps=eval_steps)\n", 547 | "print('evaluate done')\n", 548 | "\n", 549 | "print('Accuracy: %s' % results['accuracy'])\n", 550 | "print(results)\n" 551 | ] 552 | }, 553 | { 554 | "cell_type": "code", 555 | "execution_count": null, 556 | "metadata": { 557 | "collapsed": false 558 | }, 559 | "outputs": [], 560 | "source": [ 561 | "def pred_fn():\n", 562 | " sample = [ 0, 127, 1, 3, 1683, 19, 26, 17, 475, 0, 9, 0, 3, \"05db9164\", \"8947f767\", \"11c9d79e\", \"52a787c8\", \"4cf72387\", \"fbad5c96\", \"18671b18\", \"0b153874\", \"a73ee510\", \"ceb10289\", \"77212bd7\", \"79507c6b\", \"7203f04e\", \"07d13a8f\", \"2c14c412\", \"49013ffe\", \"8efede7f\", \"bd17c3da\", \"f6a3e43b\", \"a458ea53\", \"35cd95c9\", \"ad3062eb\", \"c7dc6720\", \"3fdb382b\", \"010f6491\", \"49d68486\"]\n", 563 | " sample_dict = dict(zip(FEATURE_COLUMNS, sample))\n", 564 | " \n", 565 | " for feature_name in CATEGORICAL_COLUMNS:\n", 566 | " sample_dict[feature_name] = tf.expand_dims(sample_dict[feature_name], -1)\n", 567 | " \n", 568 | " for feature_name in CONTINUOUS_COLUMNS:\n", 569 | " sample_dict[feature_name] = tf.constant(sample_dict[feature_name], dtype=tf.int32)\n", 570 | " print(sample_dict)\n", 571 | "\n", 572 | " return sample_dict\n", 573 | "\n", 574 | "m.predict(input_fn=pred_fn)" 575 | ] 576 | }, 577 | { 578 | "cell_type": "markdown", 579 | "metadata": {}, 580 | "source": [ 581 | "# Export a model optimized for inference\n", 582 | "We can upload our trained model to the Cloud Machine Learning Engine's Prediction Service, which will take care of serving our model and scaling it. The code below exports our trained model to a `saved_model.pb` file and a `variables` folder where the trained weights are stored. \n", 583 | "\n", 584 | "The `export_savedmodel()` function expects a `serving_input_fn()`, which returns the mapping from the data that the Prediction Service passes in to the data that should be fed into the trained TensorFlow prediction graph." 585 | ] 586 | }, 587 | { 588 | "cell_type": "code", 589 | "execution_count": null, 590 | "metadata": { 591 | "collapsed": true 592 | }, 593 | "outputs": [], 594 | "source": [ 595 | "from tensorflow.contrib.learn.python.learn.utils import input_fn_utils\n", 596 | "\n", 597 | "def column_to_dtype(column):\n", 598 | " if column in CATEGORICAL_COLUMNS:\n", 599 | " return tf.string\n", 600 | " else:\n", 601 | " return tf.float32\n", 602 | "\n", 603 | "def serving_input_fn():\n", 604 | " feature_placeholders = {\n", 605 | " column: tf.placeholder(column_to_dtype(column), [None])\n", 606 | " for column in FEATURE_COLUMNS\n", 607 | " }\n", 608 | " # DNNCombinedLinearClassifier expects rank 2 Tensors, but inputs should be\n", 609 | " # rank 1, so that we can provide scalars to the server\n", 610 | " features = {\n", 611 | " key: tf.expand_dims(tensor, -1)\n", 612 | " for key, tensor in feature_placeholders.items()\n", 613 | " }\n", 614 | " \n", 615 | " return input_fn_utils.InputFnOps(\n", 616 | " features, # input into graph\n", 617 | " None,\n", 618 | " feature_placeholders # tensor input converted from request \n", 619 | " )\n", 620 | " \n", 621 | " " 622 | ] 623 | }, 624 | { 625 | "cell_type": "code", 626 | "execution_count": null, 627 | "metadata": { 628 | "collapsed": false, 629 | "scrolled": true 630 | }, 631 | "outputs": [], 632 | "source": [ 633 | "# Manually export\n", 634 | "export_folder = m.export_savedmodel(\n", 635 | " export_dir_base = model_dir + '/export',\n", 636 | " input_fn=serving_input_fn\n", 637 | ")\n", 638 | "\n", 639 | "print('model exported successfully to {}'.format(export_folder))" 640 | ] 641 | }, 642 | { 643 | "cell_type": "markdown", 644 | "metadata": {}, 645 | "source": [ 646 | "# Using Experiments to manage the training workflow\n", 647 | "TensorFlow also offers an \"Experiments\" framework to help manage your training for you. Using it will take away some of the boilerplate and automate certain actions, but it's important to understand what is happening (what we did above) before using something like this.\n", 648 | "\n", 649 | "Notice that we don't need to create additional wrapper functions here, but rather, we can directly use the various functions we already defined previously. " 650 | ] 651 | }, 652 | { 653 | "cell_type": "code", 654 | "execution_count": null, 655 | "metadata": { 656 | "collapsed": false 657 | }, 658 | "outputs": [], 659 | "source": [ 660 | "from tensorflow.contrib.learn.python.learn import learn_runner\n", 661 | "from tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils\n", 662 | "\n", 663 | "\n", 664 | "# get_model(model_type = 'WIDE_AND_DEEP', model_dir=model_dir)\n", 665 | "\n", 666 | "# output_dir is an arg passed in by the learn_runner.run() call.\n", 667 | "def experiment_fn(output_dir):\n", 668 | " \n", 669 | " print(output_dir)\n", 670 | " \n", 671 | " train_input_fn = generate_input_fn(train_file, BATCH_SIZE)\n", 672 | " eval_input_fn = generate_input_fn(eval_file)\n", 673 | " my_model = get_model(model_type=MODEL_TYPE, \n", 674 | " model_dir=output_dir)\n", 675 | "\n", 676 | " experiment = tf.contrib.learn.Experiment(\n", 677 | " my_model,\n", 678 | " train_input_fn=train_input_fn,\n", 679 | " eval_input_fn=eval_input_fn,\n", 680 | " train_steps=1000\n", 681 | " ,\n", 682 | " export_strategies=[saved_model_export_utils.make_export_strategy(\n", 683 | " serving_input_fn,\n", 684 | " default_output_alternative_key=None,\n", 685 | " exports_to_keep=1\n", 686 | " )]\n", 687 | " )\n", 688 | " return experiment" 689 | ] 690 | }, 691 | { 692 | "cell_type": "code", 693 | "execution_count": null, 694 | "metadata": { 695 | "collapsed": false, 696 | "scrolled": true 697 | }, 698 | "outputs": [], 699 | "source": [ 700 | "# manually train and eval\n", 701 | "%%time\n", 702 | "\n", 703 | "exp = experiment_fn(model_dir)\n", 704 | "\n", 705 | "exp.train_and_evaluate()" 706 | ] 707 | }, 708 | { 709 | "cell_type": "code", 710 | "execution_count": null, 711 | "metadata": { 712 | "collapsed": false, 713 | "scrolled": true 714 | }, 715 | "outputs": [], 716 | "source": [ 717 | "# Run the experiment\n", 718 | "\n", 719 | "model_dir=create_model_dir(model_type=MODEL_TYPE)\n", 720 | "metrics, output_folder = learn_runner.run(experiment_fn, model_dir)\n", 721 | "\n", 722 | "print('Accuracy: {}'.format(metrics['accuracy']))\n", 723 | "print('Model exported to {}'.format(output_folder))" 724 | ] 725 | }, 726 | { 727 | "cell_type": "markdown", 728 | "metadata": {}, 729 | "source": [ 730 | "# Conclusions\n", 731 | "\n", 732 | "In this Juypter notebook, we have configured, created, and evaluated a Wide & Deep machine learning model, that combines the powers of a Linear Classifier with a Deep Neural Network, using TensorFlow's Estimator and Experiment classes.\n", 733 | "\n", 734 | "With this working example in your toolbelt, you are ready to explore the wide (and deep) world of machine learning with TensorFlow! Some ideas to help you get going:\n", 735 | "* Change the features we used today. Which columns do you think are correlated and should be crossed? Which ones do you think are just adding noise and could be removed to clean up the model?\n", 736 | "* Swap in an entirely new dataset! There are many datasets available on the web, or use a dataset you possess! Check out https://archive.ics.uci.edu/ml to find your own dataset. " 737 | ] 738 | } 739 | ], 740 | "metadata": { }, 741 | "nbformat": 4, 742 | "nbformat_minor": 2 743 | } 744 | --------------------------------------------------------------------------------