심심풀이로 만들어본 random search

Random search란 딥 러닝에 있어 최적의 학습 파라미터들을 찾는 방법들 중 하나인데요.
말 그대로 random 하게 parameter를 대입하여 학습시켜 보고, 가장 좋은 결과를 내는 parameter를 사용해서 학습을 진행하는 것이죠.

제가 만든 건 tensorflow 예제용 mnist를 응용해서 만든 간단한 코드인데요. 그냥 심심해서 시간때우기용으로 한번 만들어 보았습니다.

한번에 1천회씩 epoch를 돌려서 accuracy가 가장 높은 learning rate, batch size를 출력합니다.
epoch은 단축시킬 수 있으며, 1050이상의 그래픽카드를 사용하는 게 좋겠지요.
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

import numpy as np
import tensorflow as tf

LEARNING_MAX = 0;
BATCH_MAX = 0;
TEMP_RATE = 0;

sess = tf.InteractiveSession()

x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
randi = tf.placeholder(tf.float32)

W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)



def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)


W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)


cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))


train_step = tf.train.AdamOptimizer(randi).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

for f in range(10):
    batch_size = np.random.randint(10, 100)
    learning_rate = 10 ** np.random.uniform(-4, -3)
    sess.run(tf.global_variables_initializer())
    for i in range(1001):
        batch = mnist.train.next_batch(batch_size)
        if i == 1000:
            train_accuracy = accuracy.eval(feed_dict={
                x:batch[0], y_: batch[1],randi:learning_rate, keep_prob: 1.0})
            print("step %d, batch size %d, learning rate %g Test accuracy %g"%(i,batch_size, learning_rate, train_accuracy))

        train_step.run(feed_dict={x: batch[0], y_: batch[1],randi:learning_rate, keep_prob: 0.5})

    if TEMP_RATE <  train_accuracy:
        TEMP_RATE = train_accuracy
        LEARNING_MAX = learning_rate;
        BATCH_MAX = batch_size ;
 # 현재까지 나온 최적의 learning rate와 mnist batch size를 출력해요.
    print("Optimized Learning Rate %g, optimized Batch size %g"%(LEARNING_MAX, BATCH_MAX))

댓글 없음:

댓글 쓰기

글에 대한 의문점이나 요청점, 남기고 싶은 댓글이 있으시면 남겨 주세요. 단 악성 및 스팸성 댓글일 경우 삭제 및 차단될 수 있습니다.

모든 댓글은 검토 후 게시됩니다.

Translate