成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

如何使用TensorFlow中的高級API:Estimator、Experiment和Dataset

開發 開發工具
TensorFlow 中有許多流行的庫,如 Keras、TFLearn 和 Sonnet,它們可以讓你輕松訓練模型,而無需接觸哪些低級別函數。在本文中,我們將通過一個例子來學習如何使用一些高級構造,其中包括 Estimator、Experiment 和 Dataset。

近日,背景調查公司 Onfido 研究主管 Peter Roelants 在 Medium 上發表了一篇題為《Higher-Level APIs in TensorFlow》的文章,通過實例詳細介紹了如何使用 TensorFlow 中的高級 API(Estimator、Experiment 和 Dataset)訓練模型。值得一提的是 Experiment 和 Dataset 可以獨立使用。這些高級 API 已被***發布的 TensorFlow1.3 版收錄。

TensorFlow 中有許多流行的庫,如 Keras、TFLearn 和 Sonnet,它們可以讓你輕松訓練模型,而無需接觸哪些低級別函數。目前,Keras API 正傾向于直接在 TensorFlow 中實現,TensorFlow 也在提供越來越多的高級構造,其中的一些已經被***發布的 TensorFlow1.3 版收錄。

在本文中,我們將通過一個例子來學習如何使用一些高級構造,其中包括 Estimator、Experiment 和 Dataset。閱讀本文需要預先了解有關 TensorFlow 的基本知識。

TensorFlow

Experiment、Estimator 和 DataSet 框架和它們的相互作用(以下將對這些組件進行說明)

在本文中,我們使用 MNIST 作為數據集。它是一個易于使用的數據集,可以通過 TensorFlow 訪問。你可以在這個 gist 中找到完整的示例代碼。使用這些框架的一個好處是我們不需要直接處理圖形和會話。

Estimator

Estimator(評估器)類代表一個模型,以及這些模型被訓練和評估的方式。我們可以這樣構建一個評估器:

  1. returntf.estimator.Estimator( 
  2. model_fnmodel_fn=model_fn, # First-class function 
  3. paramsparams=params, # HParams 
  4. config=run_config # RunConfig 

為了構建一個 Estimator,我們需要傳遞一個模型函數,一個參數集合以及一些配置。

  • 參數應該是模型超參數的集合,它可以是一個字典,但我們將在本示例中將其表示為 HParams 對象,用作 namedtuple。
  • 該配置指定如何運行訓練和評估,以及如何存出結果。這些配置通過 RunConfig 對象表示,該對象傳達 Estimator 需要了解的關于運行模型的環境的所有內容。
  • 模型函數是一個 Python 函數,它構建了給定輸入的模型(見后文)。

模型函數

模型函數是一個 Python 函數,它作為***級函數傳遞給 Estimator。稍后我們就會看到,TensorFlow 也會在其他地方使用***級函數。模型表示為函數的好處在于模型可以通過實例化函數不斷重新構建。該模型可以在訓練過程中被不同的輸入不斷創建,例如:在訓練期間運行驗證測試。

模型函數將輸入特征作為參數,相應標簽作為張量。它還有一種模式來標記模型是否正在訓練、評估或執行推理。模型函數的***一個參數是超參數的集合,它們與傳遞給 Estimator 的內容相同。模型函數需要返回一個 EstimatorSpec 對象——它會定義完整的模型。

EstimatorSpec 接受預測,損失,訓練和評估幾種操作,因此它定義了用于訓練,評估和推理的完整模型圖。由于 EstimatorSpec 采用常規 TensorFlow Operations,因此我們可以使用像 TF-Slim 這樣的框架來定義自己的模型。

Experiment

Experiment(實驗)類是定義如何訓練模型,并將其與 Estimator 進行集成的方式。我們可以這樣創建一個實驗類:

  1. experiment = tf.contrib.learn.Experiment( 
  2. estimatorestimator=estimator, # Estimator 
  3. train_input_fntrain_input_fn=train_input_fn, # First-class function 
  4. eval_input_fneval_input_fn=eval_input_fn, # First-class function 
  5. train_steps=params.train_steps, # Minibatch steps 
  6. min_eval_frequency=params.min_eval_frequency, # Eval frequency 
  7. train_monitors=[train_input_hook], # Hooks for training 
  8. eval_hooks=[eval_input_hook], # Hooks for evaluation 
  9. eval_steps=None# Use evaluation feeder until its empty 

Experiment 作為輸入:

  • 一個 Estimator(例如上面定義的那個)。
  • 訓練和評估數據作為***級函數。這里用到了和前述模型函數相同的概念,通過傳遞函數而非操作,如有需要,輸入圖可以被重建。我們會在后面繼續討論這個概念。
  • 訓練和評估鉤子(hooks)。這些鉤子可以用于監視或保存特定內容,或在圖形和會話中進行一些操作。例如,我們將通過操作來幫助初始化數據加載器。
  • 不同參數解釋了訓練時間和評估時間。

一旦我們定義了 experiment,我們就可以通過 learn_runner.run 運行它來訓練和評估模型:

  1. learn_runner.run( 
  2. experiment_fnexperiment_fn=experiment_fn, # First-class function 
  3. run_configrun_config=run_config, # RunConfig 
  4. schedule="train_and_evaluate", # What to run 
  5. hparams=params # HParams 

與模型函數和數據函數一樣,函數中的學習運算符將創建 experiment 作為參數。

Dataset

我們將使用 Dataset 類和相應的 Iterator 來表示我們的訓練和評估數據,并創建在訓練期間迭代數據的數據饋送器。在本示例中,我們將使用 TensorFlow 中可用的 MNIST 數據,并在其周圍構建一個 Dataset 包裝器。例如,我們把訓練的輸入數據表示為:

  1. # Define the training inputs 
  2. defget_train_inputs(batch_size, mnist_data): 
  3. """Return the input function to get the training data. 
  4. Args: 
  5. batch_size (int): Batch size of training iterator that is returned 
  6. by the input function. 
  7. mnist_data (Object): Object holding the loaded mnist data. 
  8. Returns: 
  9. (Input function, IteratorInitializerHook): 
  10. - Function that returns (features, labels) when called. 
  11. - Hook to initialise input iterator. 
  12. """ 
  13. iterator_initializer_hook = IteratorInitializerHook() 
  14. deftrain_inputs(): 
  15. """Returns training set as Operations. 
  16. Returns: 
  17. (features, labels) Operations that iterate over the dataset 
  18. on every evaluation 
  19. """ 
  20. withtf.name_scope('Training_data'): 
  21. # Get Mnist data 
  22. images = mnist_data.train.images.reshape([-1, 28, 28, 1]) 
  23. labels = mnist_data.train.labels 
  24. # Define placeholders 
  25. images_placeholder = tf.placeholder( 
  26. images.dtype, images.shape) 
  27. labels_placeholder = tf.placeholder( 
  28. labels.dtype, labels.shape) 
  29. # Build dataset iterator 
  30. dataset = tf.contrib.data.Dataset.from_tensor_slices( 
  31. (images_placeholder, labels_placeholder)) 
  32. datasetdataset = dataset.repeat(None) # Infinite iterations 
  33. datasetdataset = dataset.shuffle(buffer_size=10000
  34. datasetdataset = dataset.batch(batch_size) 
  35. iterator = dataset.make_initializable_iterator() 
  36. next_example, next_label = iterator.get_next() 
  37. # Set runhook to initialize iterator 
  38. iterator_initializer_hook.iterator_initializer_func = 
  39. lambdasess: sess.run( 
  40. iterator.initializer, 
  41. feed_dict={images_placeholder: images, 
  42. labels_placeholder: labels}) 
  43. # Return batched (features, labels) 
  44. returnnext_example, next_label 
  45. # Return function and hook 
  46. returntrain_inputs, iterator_initializer_hook 

調用這個 get_train_inputs 會返回一個一級函數,它在 TensorFlow 圖中創建數據加載操作,以及一個 Hook 初始化迭代器。

本示例中,我們使用的 MNIST 數據最初表示為 Numpy 數組。我們創建一個占位符張量來獲取數據,再使用占位符來避免數據被復制。接下來,我們在 from_tensor_slices 的幫助下創建一個切片數據集。我們將確保該數據集運行***長時間(experiment 可以考慮 epoch 的數量),讓數據得到清晰,并分成所需的尺寸。

為了迭代數據,我們需要在數據集的基礎上創建迭代器。因為我們正在使用占位符,所以我們需要在 NumPy 數據的相關會話中初始化占位符。我們可以通過創建一個可初始化的迭代器來實現。創建圖形時,我們將創建一個自定義的 IteratorInitializerHook 對象來初始化迭代器:

  1. classIteratorInitializerHook(tf.train.SessionRunHook): 
  2. """Hook to initialise data iterator after Session is created.""" 
  3. def__init__(self): 
  4. super(IteratorInitializerHook, self).__init__() 
  5. self.iterator_initializer_func = None 
  6. defafter_create_session(self, session, coord): 
  7. """Initialise the iterator after the session has been created.""" 
  8. self.iterator_initializer_func(session) 

IteratorInitializerHook 繼承自 SessionRunHook。一旦創建了相關會話,這個鉤子就會調用 call after_create_session,并用正確的數據初始化占位符。這個鉤子會通過 get_train_inputs 函數返回,并在創建時傳遞給 Experiment 對象。

train_inputs 函數返回的數據加載操作是 TensorFlow 操作,每次評估時都會返回一個新的批處理。

運行代碼

現在我們已經定義了所有的東西,我們可以用以下命令運行代碼:

  1. python mnist_estimator.py --model_dir ./mnist_training --data_dir ./mnist_data 

如果你不傳遞參數,它將使用文件頂部的默認標志來確定保存數據和模型的位置。訓練將在終端輸出全局步長、損失、精度等信息。除此之外,實驗和估算器框架將記錄 TensorBoard 可以顯示的某些統計信息。如果我們運行:

  1. tensorboard --logdir='./mnist_training' 

我們就可以看到所有訓練統計數據,如訓練損失、評估準確性、每步時間和模型圖。

評估精度在 TensorBoard 中的可視化

在 TensorFlow 中,有關 Estimator、Experiment 和 Dataset 框架的示例很少,這也是本文存在的原因。希望這篇文章可以向大家介紹這些架構工作的原理,它們應該采用哪些抽象方法,以及如何使用它們。如果你對它們很感興趣,以下是其他相關文檔。

關于 Estimator、Experiment 和 Dataset 的注釋

  • 論文《TensorFlow Estimators: Managing Simplicity vs. Flexibility in High-Level Machine Learning Frameworks》:https://terrytangyuan.github.io/data/papers/tf-estimators-kdd-paper.pdf
  • Using the Dataset API for TensorFlow Input Pipelines:https://www.tensorflow.org/versions/r1.3/programmers_guide/datasets
  • tf.estimator.Estimator:https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator
  • tf.contrib.learn.RunConfig:https://www.tensorflow.org/api_docs/python/tf/contrib/learn/RunConfig
  • tf.estimator.DNNClassifier:https://www.tensorflow.org/api_docs/python/tf/estimator/DNNClassifier
  • tf.estimator.DNNRegressor:https://www.tensorflow.org/api_docs/python/tf/estimator/DNNRegressor
  • Creating Estimators in tf.estimator:https://www.tensorflow.org/extend/estimators
  • tf.contrib.learn.Head:https://www.tensorflow.org/api_docs/python/tf/contrib/learn/Head
  • 本文用到的 Slim 框架:https://github.com/tensorflow/models/tree/master/slim

完整示例

  1. """ to illustrate usage of tf.estimator.Estimator in TF v1.3""" 
  2. importtensorflow astf 
  3. fromtensorflow.examples.tutorials.mnist importinput_data asmnist_data 
  4. fromtensorflow.contrib importslim 
  5. fromtensorflow.contrib.learn importModeKeys 
  6. fromtensorflow.contrib.learn importlearn_runner 
  7. # Show debugging output 
  8. tf.logging.set_verbosity(tf.logging.DEBUG) 
  9. # Set default flags for the output directories 
  10. FLAGS = tf.app.flags.FLAGS 
  11. tf.app.flags.DEFINE_string( 
  12. flag_name='model_dir'default_value='./mnist_training'
  13. docstring='Output directory for model and training stats.'
  14. tf.app.flags.DEFINE_string( 
  15. flag_name='data_dir'default_value='./mnist_data'
  16. docstring='Directory to download the data to.'
  17. # Define and run experiment ############################### 
  18. defrun_experiment(argv=None): 
  19. """Run the training experiment.""" 
  20. # Define model parameters 
  21. params = tf.contrib.training.HParams( 
  22. learning_rate=0.002, 
  23. n_classes=10
  24. train_steps=5000
  25. min_eval_frequency=100 
  26. # Set the run_config and the directory to save the model and stats 
  27. run_config = tf.contrib.learn.RunConfig() 
  28. run_configrun_config = run_config.replace(model_dir=FLAGS.model_dir) 
  29. learn_runner.run( 
  30. experiment_fnexperiment_fn=experiment_fn, # First-class function 
  31. run_configrun_config=run_config, # RunConfig 
  32. schedule="train_and_evaluate", # What to run 
  33. hparams=params # HParams 
  34. defexperiment_fn(run_config, params): 
  35. """Create an experiment to train and evaluate the model. 
  36. Args: 
  37. run_config (RunConfig): Configuration for Estimator run. 
  38. params (HParam): Hyperparameters 
  39. Returns: 
  40. (Experiment) Experiment for training the mnist model. 
  41. """ 
  42. # You can change a subset of the run_config properties as 
  43. run_configrun_config = run_config.replace( 
  44. save_checkpoints_steps=params.min_eval_frequency) 
  45. # Define the mnist classifier 
  46. estimator = get_estimator(run_config, params) 
  47. # Setup data loaders 
  48. mnist = mnist_data.read_data_sets(FLAGS.data_dir, one_hot=False
  49. train_input_fn, train_input_hook = get_train_inputs
  50. batch_size=128mnistmnist_data=mnist) 
  51. eval_input_fn, eval_input_hook = get_test_inputs
  52. batch_size=128mnistmnist_data=mnist) 
  53. # Define the experiment 
  54. experiment = tf.contrib.learn.Experiment( 
  55. estimatorestimator=estimator, # Estimator 
  56. train_input_fntrain_input_fn=train_input_fn, # First-class function 
  57. eval_input_fneval_input_fn=eval_input_fn, # First-class function 
  58. train_steps=params.train_steps, # Minibatch steps 
  59. min_eval_frequency=params.min_eval_frequency, # Eval frequency 
  60. train_monitors=[train_input_hook], # Hooks for training 
  61. eval_hooks=[eval_input_hook], # Hooks for evaluation 
  62. eval_steps=None# Use evaluation feeder until its empty 
  63. returnexperiment 
  64. # Define model ############################################ 
  65. defget_estimator(run_config, params): 
  66. """Return the model as a Tensorflow Estimator object. 
  67. Args: 
  68. run_config (RunConfig): Configuration for Estimator run. 
  69. params (HParams): hyperparameters. 
  70. """ 
  71. returntf.estimator.Estimator( 
  72. model_fnmodel_fn=model_fn, # First-class function 
  73. paramsparams=params, # HParams 
  74. config=run_config # RunConfig 
  75. defmodel_fn(features, labels, mode, params): 
  76. """Model function used in the estimator. 
  77. Args: 
  78. features (Tensor): Input features to the model. 
  79. labels (Tensor): Labels tensor for training and evaluation. 
  80. mode (ModeKeys): Specifies if training, evaluation or prediction. 
  81. params (HParams): hyperparameters. 
  82. Returns: 
  83. (EstimatorSpec): Model to be run by Estimator. 
  84. """ 
  85. is_training = mode == ModeKeys.TRAIN 
  86. # Define model's architecture 
  87. logits = architecture(features, is_trainingis_training=is_training) 
  88. predictions = tf.argmax(logits, axis=-1) 
  89. # Loss, training and eval operations are not needed during inference. 
  90. loss = None 
  91. train_op = None 
  92. eval_metric_ops = {} 
  93. ifmode != ModeKeys.INFER: 
  94. loss = tf.losses.sparse_softmax_cross_entropy( 
  95. labels=tf.cast(labels, tf.int32), 
  96. logitslogits=logits) 
  97. train_op = get_train_op_fn(loss, params) 
  98. eval_metric_ops = get_eval_metric_ops(labels, predictions) 
  99. returntf.estimator.EstimatorSpec( 
  100. modemode=mode, 
  101. predictionspredictions=predictions, 
  102. lossloss=loss, 
  103. train_optrain_op=train_op, 
  104. eval_metric_opseval_metric_ops=eval_metric_ops 
  105. defget_train_op_fn(loss, params): 
  106. """Get the training Op. 
  107. Args: 
  108. loss (Tensor): Scalar Tensor that represents the loss function. 
  109. params (HParams): Hyperparameters (needs to have `learning_rate`) 
  110. Returns: 
  111. Training Op 
  112. """ 
  113. returntf.contrib.layers.optimize_loss( 
  114. lossloss=loss, 
  115. global_step=tf.contrib.framework.get_global_step(), 
  116. optimizer=tf.train.AdamOptimizer, 
  117. learning_rate=params.learning_rate 
  118. defget_eval_metric_ops(labels, predictions): 
  119. """Return a dict of the evaluation Ops. 
  120. Args: 
  121. labels (Tensor): Labels tensor for training and evaluation. 
  122. predictions (Tensor): Predictions Tensor. 
  123. Returns: 
  124. Dict of metric results keyed by name. 
  125. """ 
  126. return{ 
  127. 'Accuracy': tf.metrics.accuracy( 
  128. labelslabels=labels, 
  129. predictionspredictions=predictions, 
  130. name='accuracy'
  131. defarchitecture(inputs, is_training, scope='MnistConvNet'): 
  132. """Return the output operation following the network architecture. 
  133. Args: 
  134. inputs (Tensor): Input Tensor 
  135. is_training (bool): True iff in training mode 
  136. scope (str): Name of the scope of the architecture 
  137. Returns: 
  138. Logits output Op for the network. 
  139. """ 
  140. withtf.variable_scope(scope): 
  141. withslim.arg_scope( 
  142. [slim.conv2d, slim.fully_connected], 
  143. weights_initializer=tf.contrib.layers.xavier_initializer()): 
  144. net = slim.conv2d(inputs, 20, [5, 5], padding='VALID'
  145. scope='conv1'
  146. net = slim.max_pool2d(net, 2, stride=2scope='pool2'
  147. net = slim.conv2d(net, 40, [5, 5], padding='VALID'
  148. scope='conv3'
  149. net = slim.max_pool2d(net, 2, stride=2scope='pool4'
  150. net = tf.reshape(net, [-1, 4* 4* 40]) 
  151. net = slim.fully_connected(net, 256, scope='fn5'
  152. net = slim.dropout(net, is_trainingis_training=is_training, 
  153. scope='dropout5'
  154. net = slim.fully_connected(net, 256, scope='fn6'
  155. net = slim.dropout(net, is_trainingis_training=is_training, 
  156. scope='dropout6'
  157. net = slim.fully_connected(net, 10, scope='output'
  158. activation_fn=None
  159. returnnet 
  160. # Define data loaders ##################################### 
  161. classIteratorInitializerHook(tf.train.SessionRunHook): 
  162. """Hook to initialise data iterator after Session is created.""" 
  163. def__init__(self): 
  164. super(IteratorInitializerHook, self).__init__() 
  165. self.iterator_initializer_func = None 
  166. defafter_create_session(self, session, coord): 
  167. """Initialise the iterator after the session has been created.""" 
  168. self.iterator_initializer_func(session) 
  169. # Define the training inputs 
  170. defget_train_inputs(batch_size, mnist_data): 
  171. """Return the input function to get the training data. 
  172. Args: 
  173. batch_size (int): Batch size of training iterator that is returned 
  174. by the input function. 
  175. mnist_data (Object): Object holding the loaded mnist data. 
  176. Returns: 
  177. (Input function, IteratorInitializerHook): 
  178. - Function that returns (features, labels) when called. 
  179. - Hook to initialise input iterator. 
  180. """ 
  181. iterator_initializer_hook = IteratorInitializerHook() 
  182. deftrain_inputs(): 
  183. """Returns training set as Operations. 
  184. Returns: 
  185. (features, labels) Operations that iterate over the dataset 
  186. on every evaluation 
  187. """ 
  188. withtf.name_scope('Training_data'): 
  189. # Get Mnist data 
  190. images = mnist_data.train.images.reshape([-1, 28, 28, 1]) 
  191. labels = mnist_data.train.labels 
  192. # Define placeholders 
  193. images_placeholder = tf.placeholder( 
  194. images.dtype, images.shape) 
  195. labels_placeholder = tf.placeholder( 
  196. labels.dtype, labels.shape) 
  197. # Build dataset iterator 
  198. dataset = tf.contrib.data.Dataset.from_tensor_slices( 
  199. (images_placeholder, labels_placeholder)) 
  200. datasetdataset = dataset.repeat(None) # Infinite iterations 
  201. datasetdataset = dataset.shuffle(buffer_size=10000
  202. datasetdataset = dataset.batch(batch_size) 
  203. iterator = dataset.make_initializable_iterator() 
  204. next_example, next_label = iterator.get_next() 
  205. # Set runhook to initialize iterator 
  206. iterator_initializer_hook.iterator_initializer_func = 
  207. lambdasess: sess.run( 
  208. iterator.initializer, 
  209. feed_dict={images_placeholder: images, 
  210. labels_placeholder: labels}) 
  211. # Return batched (features, labels) 
  212. returnnext_example, next_label 
  213. # Return function and hook 
  214. returntrain_inputs, iterator_initializer_hook 
  215. defget_test_inputs(batch_size, mnist_data): 
  216. """Return the input function to get the test data. 
  217. Args: 
  218. batch_size (int): Batch size of training iterator that is returned 
  219. by the input function. 
  220. mnist_data (Object): Object holding the loaded mnist data. 
  221. Returns: 
  222. (Input function, IteratorInitializerHook): 
  223. - Function that returns (features, labels) when called. 
  224. - Hook to initialise input iterator. 
  225. """ 
  226. iterator_initializer_hook = IteratorInitializerHook() 
  227. deftest_inputs(): 
  228. """Returns training set as Operations. 
  229. Returns: 
  230. (features, labels) Operations that iterate over the dataset 
  231. on every evaluation 
  232. """ 
  233. withtf.name_scope('Test_data'): 
  234. # Get Mnist data 
  235. images = mnist_data.test.images.reshape([-1, 28, 28, 1]) 
  236. labels = mnist_data.test.labels 
  237. # Define placeholders 
  238. images_placeholder = tf.placeholder( 
  239. images.dtype, images.shape) 
  240. labels_placeholder = tf.placeholder( 
  241. labels.dtype, labels.shape) 
  242. # Build dataset iterator 
  243. dataset = tf.contrib.data.Dataset.from_tensor_slices( 
  244. (images_placeholder, labels_placeholder)) 
  245. datasetdataset = dataset.batch(batch_size) 
  246. iterator = dataset.make_initializable_iterator() 
  247. next_example, next_label = iterator.get_next() 
  248. # Set runhook to initialize iterator 
  249. iterator_initializer_hook.iterator_initializer_func = 
  250. lambdasess: sess.run( 
  251. iterator.initializer, 
  252. feed_dict={images_placeholder: images, 
  253. labels_placeholder: labels}) 
  254. returnnext_example, next_label 
  255. # Return function and hook 
  256. returntest_inputs, iterator_initializer_hook 
  257. # Run ############################################## 
  258. if__name__ == "__main__": 
  259. tf.app.run( 
  260. main=run_experiment 

推理訓練模式

在訓練模型后,我們可以運行 estimateator.predict 來預測給定圖像的類別。可使用以下代碼示例。

  1. """ to illustrate inference of a trained tf.estimator.Estimator. 
  2. NOTE: This is dependent on mnist_estimator.py which defines the model. 
  3. mnist_estimator.py can be found at: 
  4. https://gist.github.com/peterroelants/9956ec93a07ca4e9ba5bc415b014bcca 
  5. """ 
  6. importnumpy asnp 
  7. importskimage.io 
  8. importtensorflow astf 
  9. frommnist_estimator importget_estimator 
  10. # Set default flags for the output directories 
  11. FLAGS =tf.app.flags.FLAGS 
  12. tf.app.flags.DEFINE_string( 
  13. flag_name='saved_model_dir',default_value='./mnist_training'
  14. docstring='Output directory for model and training stats.'
  15. # MNIST sample images 
  16. IMAGE_URLS =[ 
  17. 'https://i.imgur.com/SdYYBDt.png',# 0 
  18. 'https://i.imgur.com/Wy7mad6.png',# 1 
  19. 'https://i.imgur.com/nhBZndj.png',# 2 
  20. 'https://i.imgur.com/V6XeoWZ.png',# 3 
  21. 'https://i.imgur.com/EdxBM1B.png',# 4 
  22. 'https://i.imgur.com/zWSDIuV.png',# 5 
  23. 'https://i.imgur.com/Y28rZho.png',# 6 
  24. 'https://i.imgur.com/6qsCz2W.png',# 7 
  25. 'https://i.imgur.com/BVorzCP.png',# 8 
  26. 'https://i.imgur.com/vt5Edjb.png',# 9 
  27. definfer(argv=None): 
  28. """Run the inference and print the results to stdout.""" 
  29. params =tf.contrib.training.HParams()# Empty hyperparameters 
  30. # Set the run_config where to load the model from 
  31. run_config =tf.contrib.learn.RunConfig() 
  32. run_configrun_config =run_config.replace(model_dir=FLAGS.saved_model_dir) 
  33. # Initialize the estimator and run the prediction 
  34. estimator =get_estimator(run_config,params) 
  35. result =estimator.predict(input_fn=test_inputs
  36. forr inresult: 
  37. print(r) 
  38. deftest_inputs(): 
  39. """Returns training set as Operations. 
  40. Returns: 
  41. (features, ) Operations that iterate over the test set. 
  42. """ 
  43. withtf.name_scope('Test_data'): 
  44. images =tf.constant(load_images(),dtype=np.float32) 
  45. dataset =tf.contrib.data.Dataset.from_tensor_slices((images,)) 
  46. # Return as iteration in batches of 1 
  47. returndataset.batch(1).make_one_shot_iterator().get_next() 
  48. defload_images(): 
  49. """Load MNIST sample images from the web and return them in an array. 
  50. Returns: 
  51. Numpy array of size (10, 28, 28, 1) with MNIST sample images. 
  52. """ 
  53. images =np.zeros((10,28,28,1)) 
  54. foridx,url inenumerate(IMAGE_URLS): 
  55. images[idx,:,:,0]=skimage.io.imread(url) 
  56. returnimages 
  57. # Run ############################################## 
  58. if__name__ =="__main__": 
  59. tf.app.run(main=infer

原文:https://medium.com/onfido-tech/higher-level-apis-in-tensorflow-67bfb602e6c0

【本文是51CTO專欄機構“機器之心”的原創譯文,微信公眾號“機器之心( id: almosthuman2014)”】

 

戳這里,看該作者更多好文

責任編輯:趙寧寧 來源: 51CTO專欄
相關推薦

2024-02-17 09:00:00

機器學習AI自動檢測人工智能

2024-02-18 08:00:00

PythonAI多模態模型API

2016-12-06 08:51:48

深度學習TensorFlow機器學習

2023-11-23 08:00:00

OpenAILangChain

2023-06-26 10:51:56

開源API

2009-09-14 19:58:47

DataSet和Dat

2020-10-27 09:37:43

PyTorchTensorFlow機器學習

2017-11-01 15:13:49

TensorFlow神經網絡深度學習

2017-08-29 13:50:03

TensorFlow深度學習神經網絡

2017-03-27 16:18:30

神經網絡TensorFlow人工智能

2020-01-16 11:42:45

PyramidCornicePython Web

2021-11-02 09:40:50

TensorFlow機器學習人工智能

2017-11-10 12:45:16

TensorFlowPython神經網絡

2017-09-12 16:31:21

TensorFlowLSTMCNN

2023-05-15 09:14:38

2022-05-31 07:40:41

ArctypeFeather.jsSQLite

2011-12-19 08:57:46

PhoneGapNativeContr

2017-05-30 16:16:38

TensorFlow候選采樣深度學習

2009-12-29 16:50:13

ADO DataSet

2018-08-02 08:45:48

物聯網機器學習Tensorflow
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 日日噜噜噜夜夜爽爽狠狠视频, | av激情在线 | 日本又色又爽又黄又高潮 | 亚洲国产欧美日韩 | 天天色综 | 91久久久久久 | 四虎永久免费影院 | 欧美精品欧美精品系列 | 一级黄色毛片子 | 久久久国产精品 | 亚洲精品在线观看网站 | 成人免费视频网站在线看 | 成人午夜精品 | 亚洲一区二区三区福利 | 久久综合久久综合久久综合 | www97影院| 成人国产在线视频 | 天天干天天色 | 国产免费一区 | 伊人狠狠操 | 超碰在线人 | 久久久区 | 四虎永久免费黄色影片 | 在线观看一区 | 日韩a| 国产一区二区在线视频 | 皇色视频在线 | 91在线一区 | 色综合久 | 国产精品福利视频 | 欧美日韩电影一区 | 欧美亚洲一级 | 中文字幕国产视频 | 国产精品夜夜夜一区二区三区尤 | 欧美日本一区 | 91久久久精品国产一区二区蜜臀 | 久久福利网站 | 亚洲97 | 亚洲精品日韩综合观看成人91 | 亚洲精品久久久久久久久久久久久 | 久久成人综合 |