TensorFlow Core tutorial も今回で最後です。Estimator というものを使ってみました。



https://www.tensorflow.org/get_started/get_started#tfestimator


うーん、正直よく分からないのですが、損失関数が最小になるように条件を求め、かつそれを評価するためのツールといったところでしょうか?

とりあえずコードを見よう見まねで書いてみました。Basic Usage と A custom model の二つがありますが、A custom model のほうが見通しがよいので試してみました。


import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
import numpy as np

# delare list of features,
def model_fn(features, labels, mode):
# Build a linear model
W = tf.get_variable("W", [1], dtype=tf.float64)
b = tf.get_variable("b", [1], dtype=tf.float64)
y = W * features['x'] + b
loss = tf.reduce_sum(tf.square(y - labels))

# training to minimize loss
global_step = tf.train.get_global_step()
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = tf.group(optimizer.minimize(loss), tf.assign_add(global_step, 1))

return tf.estimator.EstimatorSpec(mode=mode ,predictions=y
,loss=loss ,train_op=train)


estimator = tf.estimator.Estimator(model_fn=model_fn)

# defin data sets
x_train = np.array([ 1.0 , 2.0 , 3.0 , 4.0])
y_train = np.array([ 0.0 ,-1.0 ,-2.0 ,-3.0])
x_eval = np.array([ 2.0 , 5.0 , 8.0 , 1.0])
y_eval = np.array([-1.01,-4.1 ,-7.0 , 0.0])

input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_train} ,y_train ,batch_size=4 ,num_epochs=None ,shuffle=True)

train_input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_train} ,y_train ,batch_size=4 ,num_epochs=1000 ,shuffle=False)

eval_input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_eval } ,y_eval ,batch_size=4 ,num_epochs=1000 ,shuffle=False)

# train
estimator.train(input_fn=input_fn ,steps=1000)

# evaluate the model defined
train_metrics = estimator.evaluate(input_fn=train_input_fn)
eval_metrics = estimator.evaluate(input_fn=eval_input_fn)
print("train metrics: %r"% train_metrics)
print("eval metrics: %r"% eval_metrics)


実行結果がこちら。


C:\Users\Taro\Documents\TensorFlow>python estimator.py
WARNING:tensorflow:Using temporary folder as model directory: C:\Users\Taro\AppData\Local\Temp\tmp_ad4se
train metrics: {'global_step': 1000, 'loss': 1.265121e-11}
eval metrics: {'global_step': 1000, 'loss': 0.010100436}



うーん、たしかにlossが小さくなるようになったようです。Eval は実際のデータで試してみた値なのかな。説明がほとんどないのでよく分かりません。

とりあえず、わざわざループを作らなくても損失関数を最小にできる便利なツールがある程度で理解して先に進もうと思います。
σ(ー_ ー;)ワカラン





TensorFlowはじめました 実践!最新Googleマシンラーニング (NextPublishing)

  • 出版社/メーカー: インプレスR&D
  • 発売日: 2016/07/29
  • メディア: Kindle版



ゼロから作るDeep Learning ―Pythonで学ぶディープラーニングの理論と実装

  • 作者: 斎藤 康毅
  • 出版社/メーカー: オライリージャパン
  • 発売日: 2016/09/24
  • メディア: 単行本(ソフトカバー)



TensorFlow機械学習クックブック Pythonベースの活用レシピ60+ (impress top gear)

  • 作者: Nick McClure
  • 出版社/メーカー: インプレス
  • 発売日: 2017/08/14
  • メディア: 単行本(ソフトカバー)