반응형


입력 데이터를 사용한 훈련이 완료된 후, 변수(tf.Variable)에 저장되어 있는 모델 파라미터를 파일로 저장했다가 필요시 불러와 사용하는 방법을 다루고 있습니다.


MNIST를 기반으로 손글씨를 인식시키려고 진행하는 도중에 매번 훈련 데이터를 가지고 최적화 및 손실 계산을 할 필요가 없지 않을까 하다가  찾아보게 되었습니다.



다음 사이트에 있는 텐서플로우 예제들을 공부한 결과를 비정기적으로 올리고 있습니다.

https://github.com/aymericdamien/TensorFlow-Examples







텐서플로우 2.0에서 텐서플로우 1.x 코드를 실행하는 방법을 설명합니다. 


Tensorflow 2.0에서 Tensorflow 1.x 코드 실행하기

https://webnautes.tistory.com/1393



기존 포스팅의 코드를 둘로 나누어서 훈련이 끝나면 파라미터를 파일로 저장시키는 코드와   파일로부터 파라미터를 읽어와서 정확도를 계산하는 코드로 분리했습니다.

실제론 두번째 코드는 손글씨 이미지를 불러와서 손글씨를 인식하는 것이 되어야 하지만 다음 포스팅으로 미루게되어 이렇게 해보게 되었습니다.



예제로 배우는 텐서플로우 강좌 - 6. Logistic Regression( MNIST 데이터를 이용한 손글씨 인식 )

http://webnautes.tistory.com/1236





모델 파라미터 저장하기


최적화가 완료된 후, 변수 W, b에 저장되어 있는 파라미터를 파일로  저장합니다. 세션내에서 실행시켜야 합니다.


model_path = "/tmp/model.saved" # 모델을 저장할 경로와 파일 이름
saver = tf.train.Saver()

save_path = saver.save(sess, model_path)
print("Model saved in file: %s" % save_path)




전체 코드 입니다.


import tensorflow as tf



#---------------------------------------------------------------------------------------------------------- 입력
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)



#---------------------------------------------------------------------------------------------------------- 모델
x = tf.placeholder(tf.float32, [None, 784])

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

y_model = tf.matmul(x, W) + b



#---------------------------------------------------------------------------------------------------------- 라벨
y = tf.placeholder(tf.float32, [None, 10])



#---------------------------------------------------------------------------------------------------------- loss와 optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=y_model))
optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cost) # learning_rate = 0.01



#---------------------------------------------------------------------------------------------------------- 세션
sess = tf.Session()


sess.run(tf.global_variables_initializer())


for epoch in range(25):
   avg_cost = 0.

   total_batch = int(mnist.train.num_examples / 100)
   for i in range(total_batch):
       batch_xs, batch_ys = mnist.train.next_batch(100)
       _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs, y: batch_ys})
       avg_cost += c / total_batch

   print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))


print("최적화 완료")



#---------------------------------------------------------------------------------------------------- 모델 파라미터 저장
model_path = "/tmp/model.saved" # 모델을 저장할 경로와 파일 이름
saver = tf.train.Saver()

save_path = saver.save(sess, model_path)
print("Model saved in file: %s" % save_path)

sess.close()




..


..



모델 파라미터 불러오기


모델 파라미터를 변수(tf.Variable) W, b로 가져오는 코드입니다.  세션내에서 실행해야 합니다.


model_path = "/tmp/model.saved"
saver = tf.train.Saver()

saver.restore(sess, model_path)
print("Model restored from file: %s" % model_path)




전체 코드입니다.


import tensorflow as tf



#---------------------------------------------------------------------------------------------------------- 입력
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)



#---------------------------------------------------------------------------------------------------------- 모델
x = tf.placeholder(tf.float32, [None, 784])

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

y_model = tf.matmul(x, W) + b


#---------------------------------------------------------------------------------------------------------- 라벨
y = tf.placeholder(tf.float32, [None, 10])



#---------------------------------------------------------------------------------------------------------- 세션
sess = tf.Session()


# 저장된 모델 파라미터를 가져옵니다.
model_path = "/tmp/model.saved"
saver = tf.train.Saver()

saver.restore(sess, model_path)
print("Model restored from file: %s" % model_path)


# 정확도를 계산합니다.
correct_prediction = tf.equal(tf.argmax(y_model, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}))

sess.close()




원본 코드

https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/logistic_regression.py


마지막 업데이트 - 2018. 8. 31



문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts