Tensorflow Version 1 tune 간단 예제

2020. 2. 2. 16:49분석 Python/Tensorflow

728x90

광고 한 번만 눌러주세요 블로그 운영에 큰 힘이 됩니다! :)

 

최근에 optuna를 쓰다가 먼가 cpu를 잘 안 쓰는 것 같아서 다른 것을 고민하다가 tune을 발견했다.

https://towardsdatascience.com/fast-hyperparameter-tuning-at-scale-d428223b081c

 

Tune: a Python library for fast hyperparameter tuning at any scale

How do you tune hyperparameters with thousands of cores in just 18 lines of code?

towardsdatascience.com

일단 표 자체에서는 search algorithms 과 fault tolerance 차이밖에 없긴 해서, 더 cpu를 효율적으로 쓰는지는 모르겠지만, medium 글 결과를 보니 효율적으로 쓰는 것 같아서, 기대감에 도전해보기로 했다.

저기 글에선 다른 Framework를 지원해준다고 했지만, 아쉽게도 tensorflow 2부터였다...(언젠가는 넘어가야지..)

필자는 거의 tensorflow version 1을 주로 쓰다 보니, 먼가 고민을 해야 했다.
그래서 지금 원래 코드에서는 안 돌아가서 간단한 코드를 만들어 테스트를 해봤다.

https://ray.readthedocs.io/en/latest/search.html?q=tune.run&check_keywords=yes&area=default

 

Search — Ray 0.9.0.dev0 documentation

© Copyright 2019, The Ray Team Revision cc43c9c1.

ray.readthedocs.io

 

일단은 간단하게 그래프를 만들고 w를 찾는 것을 해봤다.
하나 알게 된 점은 tune을 쓸 때는 simplemodel 함수 안에서 package를 import 해야 에러가 안 난다.

https://ray.readthedocs.io/en/latest/using-ray-with-tensorflow.html

 

Best Practices: Ray with Tensorflow — Ray 0.9.0.dev0 documentation

Best Practices: Ray with Tensorflow This document describes best practices for using the Ray core APIs with TensorFlow. Ray also provides higher-level utilities for working with Tensorflow, such as distributed training APIs (training tensorflow example), T

ray.readthedocs.io

원래 필자의 코드는 여러 개로 분리되어 있고 다른 곳에서 import 해서 사용하고 있는데... 
class로 만들어서 다시 도전해봐야겠다. 
아무튼 간단한 모델을 만들어봤다.

def simplemodel(config) :
    import tensorflow as tf
    w = config["node"]
    print("="*10)
    print(w)
    print("="*10)
    tf.reset_default_graph()
    a = tf.constant([w], dtype=tf.float32,shape=())
    loss = (5-a)**2
    config=tf.ConfigProto(log_device_placement=True)
    config.gpu_options.allow_growth = True
    sess = tf.Session(config = config)
    sess.run(tf.global_variables_initializer())
    loss2 = sess.run(loss, feed_dict={a:w})
    tune.track.log(loss=loss2,done=True)
    

if __name__ == '__main__':
    from ray.tune.schedulers import AsyncHyperBandScheduler
    ray.init()
    sched = AsyncHyperBandScheduler(
        metric="loss",
        mode="min",
        max_t=10,
        grace_period=2)
    tune.run(
        simplemodel,
        config={ "node" : tune.uniform(0,10)},
        name="tune",
        stop={
            "loss": 0.0
        },
        num_samples=2,
        scheduler=sched)    

잘 돌아간다!



다음에는 회귀모형을 만들어서 구해봤다.

data = np.random.normal(size = (100,2))
true = 5*np.random.normal(size = (100,1))

def simplemodel(space) :
    import tensorflow as tf
    w = space["node"]
    print("="*10)
    print(w)
    print("="*10)
    tf.reset_default_graph()
    X = tf.placeholder(tf.float32,shape=[None,2], name= "X")
    y = tf.placeholder(tf.float32,shape=[None,1], name= "y")
    W = tf.get_variable("w", shape=[2,w],dtype= tf.float32)
    W2 = tf.get_variable("ww", shape=[w,1], dtype = tf.float32)
    layer = tf.matmul(X , W)
    logit = tf.matmul(layer , W2)
    loss = tf.reduce_mean((y-logit)**2)
    optimizer = tf.train.AdamOptimizer(0.005)
    solver = optimizer.minimize(loss ,var_list = tf.trainable_variables() )
    config=tf.ConfigProto(log_device_placement=True)
    config.gpu_options.allow_growth = True
    sess = tf.Session(config = config)
    sess.run(tf.global_variables_initializer())
    for i in range(100) :
        _ , loss2 = sess.run([solver , loss], feed_dict={X:data , y : true})
    tune.track.log(loss=loss2,done=True)
    
if __name__ == '__main__':
    from ray.tune.schedulers import AsyncHyperBandScheduler
    from ray.tune.suggest.hyperopt import HyperOptSearch
    from hyperopt import hp
    space = {
        "node" : hp.randint("node",5,10)
    }
    algo = HyperOptSearch(
            space,
            max_concurrent=4,
            metric="loss",
            mode="min",)
    # points_to_evaluate=current_best_params
    ray.init()
    sched = AsyncHyperBandScheduler(
        metric="loss",
        mode="min",
        max_t=100,
        grace_period=2)
    analysis = tune.run(
        simplemodel,
        name="tune",
        search_alg= algo,
        stop={
            "loss": 0.0
        },
        num_samples=100,
        scheduler=sched)    
        
df = analysis.dataframe()
df.sort_values("loss")
analysis.get_best_config(metric="loss")

다행히 돌아갔다 ㅠㅠ 이젠 class를 만들어서 다시 도전해봐야겠다.

728x90