tf.contrib.learn


tf.contrib.learn은 다음을 포함하여 머신러닝의 메커니즘을 단순화하는 상위 레벨의 TensorFlow 라이브러리입니다.

  • running training loops
  • running evaluation loops
  • managing data sets
  • managing feeding

tf.contrib.learn은 많은 일반 모델을 정의합니다. 



Basic usage


tf.contrib.learn을 사용하면 linear regression 프로그램이 얼마나 단순해지는지 알 수 있습니다.

import tensorflow as tf
# NumPy is often used to load, manipulate and preprocess data.
import numpy as np

# Declare list of features. We only have one real-valued feature. There are many
# other types of columns that are more complicated and useful.
features
= [tf.contrib.layers.real_valued_column("x", dimension=1)]

# An estimator is the front end to invoke training (fitting) and evaluation
# (inference). There are many predefined types like linear regression,
# logistic regression, linear classification, logistic classification, and
# many neural network classifiers and regressors. The following code
# provides an estimator that does linear regression.
estimator
= tf.contrib.learn.LinearRegressor(feature_columns=features)

# TensorFlow provides many helper methods to read and set up data sets.
# Here we use `numpy_input_fn`. We have to tell the function how many batches
# of data (num_epochs) we want and how big each batch should be.
x
= np.array([1., 2., 3., 4.])
y
= np.array([0., -1., -2., -3.])
input_fn
= tf.contrib.learn.io.numpy_input_fn({"x":x}, y, batch_size=4,
                                              num_epochs
=1000)

# We can invoke 1000 training steps by invoking the `fit` method and passing the
# training data set.
estimator
.fit(input_fn=input_fn, steps=1000)

# Here we evaluate how well our model did. In a real example, we would want
# to use a separate validation and testing data set to avoid overfitting.
estimator
.evaluate(input_fn=input_fn)

실행 결과는 다음과 같습니다. 

    {'global_step': 1000, 'loss': 1.9650059e-11}



A custom model


tf.contrib.learn은 미리 정의된 모델들만 제공하지 않습니다. TensorFlow에 내장되어 있지 않은 커스텀 모델을 만들 수 있습니다. tf.contrib.learn의 data set, feeding, training 등 높은 수준의 추상화는 유지할 수 있습니다. 설명을 위해, 낮은 수준은 TensorFlow API를 이용하여 linear regression에 대한 equivalent 모델을 구현하는 방법을 나타냅니다.


tf.contrib.leanr을 이용하여 커스텀 모델을 정의하기 위해, tf.contrib.learn.Estimator를 사용해야 합니다. tf.contrib.learn.LinearRegressor는 tf.contrib.learn.Estimator의 서브 클래스입니다. Estimator를 sub-classing하는 대신에 Estimator에 model_fn 함수를 제공합니다. tf.contrib.learn은 prediction, training step, loss를 evaluate할 수 있는 방법을 알려줍니다. 코드는 다음과 같습니다. 

import numpy as np
import tensorflow as tf
# Declare list of features, we only have one real-valued feature
def model(features, labels, mode):
 
# Build a linear model and predict values
  W
= tf.get_variable("W", [1], dtype=tf.float64)
  b
= tf.get_variable("b", [1], dtype=tf.float64)
  y
= W*features['x'] + b
 
# Loss sub-graph
  loss
= tf.reduce_sum(tf.square(y - labels))
 
# Training sub-graph
  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))
 
# ModelFnOps connects subgraphs we built to the
 
# appropriate functionality.
 
return tf.contrib.learn.ModelFnOps(
      mode
=mode, predictions=y,
      loss
= loss,
      train_op
=train)

estimator
= tf.contrib.learn.Estimator(model_fn=model)
# define our data set
x
=np.array([1., 2., 3., 4.])
y
=np.array([0., -1., -2., -3.])
input_fn
= tf.contrib.learn.io.numpy_input_fn({"x": x}, y, 4, num_epochs=1000)

# train
estimator
.fit(input_fn=input_fn, steps=1000)
# evaluate our model
print(estimator.evaluate(input_fn=input_fn, steps=10))

결과는 다음과 같습니다.

{'loss': 5.9819476e-11, 'global_step': 1000}

커스텀 모델 함수의 내용이 낮은 수준 API의 수동 모델 training loop와 얼마나 유사한지 주목하세요.



출처


'머신러닝 > TensorFlow' 카테고리의 다른 글

tf.train API  (0) 2017.03.07
TensorFlow Core tutorial  (0) 2017.02.28
설치하기  (2) 2017.02.21
TensorFlow란?  (0) 2017.02.21

+ Recent posts