Created
November 10, 2017 23:35
-
-
Save oiehot/fbc6fc6b7f920e7df892be596262f8d8 to your computer and use it in GitHub Desktop.
Tensorflow Custom Estimator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import tensorflow as tf | |
# 커스텀 Estimator 모델(func) | |
def model_fn(features, labels, mode): | |
W = tf.get_variable('W', [1], dtype=tf.float64) # tf.get_variable(): Gets an existing variable with parameter or create a new one. | |
b = tf.get_variable('b', [1], dtype=tf.float64) | |
y = W * features['x'] + b | |
# loss(오차) 서브 그래프 | |
loss = tf.reduce_sum(tf.square(y - labels)) # labels: 지도 해답? | |
# 훈련 서브 그래프 | |
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)) # tf.group(): Create an op that groups multiple operations. | |
return tf.estimator.EstimatorSpec( | |
mode = mode, | |
predictions = y, | |
loss = loss, | |
train_op = train) | |
# 커스텀 Estimator | |
estimator = tf.estimator.Estimator(model_fn = model_fn) | |
# 데이터 세트 | |
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) | |
# 훈련 | |
estimator.train(input_fn=input_fn, steps=1000) | |
# 결과 | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much for sharing this code snippet!!!! I've been looking for such an example!