공식 사이트 : https://www.tensorflow.org/versions/r0.10/how_tos/variables/index.html#variables-creation-initialization-saving-and-loading
공식사이트에 있는 튜토리얼 내용을 직접 예제를 만들어 보면서 그 내용을 정리
하고자 함
가 . Variables 의 생성과 저장
시작하기에 앞서 Variables 에 대해서 설명할 필요가 있다. 모델을 구성하는 주요 값인
WEIGHT , BIAS 와 같은 학습 값의 구조, 초기 값 등을 정의하는 변수이다.
[초기값 정의 방법]

[chap1_save_variables.py]
변수를 생성하고 파일로 저장하는 예제 코드
# -*- coding: utf-8 -*-
import tensorflow as tf
def main(_):
# 탠소플로우 변수 생성 , 파이선 리턴 값은 tf.Variable 이 된다.
weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35),name="weights")
biases = tf.Variable(tf.zeros([200]), name="biases")
# 위에 정의한 변수를 변형하여 다른 이름으로 재 정의 할 수 있다
w2 = tf.Variable(weights.initialized_value(), name="w2")
w_twice = tf.Variable(weights.initialized_value() * 2.0, name="w_twice")
temp1 = tf.constant(5.0)
temp2 = tf.constant(10.0)
temp3 = tf.add(temp1, temp2)
# 값을 찍어 보면 탠소 플로우 베리어블 객체의 내용을 확인 가능
print("weight : " + str(weights.initialized_value()))
print("biases : " + str(biases.initialized_value()))
print("w2 : " + str(w2.initialized_value()))
print("w_twice : " + str(w_twice.initialized_value()))
print("temp1 : " + str(temp1))
print("temp2 : " + str(temp2))
print("temp3 : " + str(temp3))
# 위에 정의한 변수들을 실제로 탠소플로우 모델 메모리에 등록한다
init_op = tf.initialize_all_variables()
print(init_op)
# 값을 직어 보면 아래와 같다
# name: "init"
# op: "NoOp"
# input: "^weights/Assign"
# input: "^biases/Assign"
# input: "^w2/Assign"
# input: "^w_twice/Assign"
#저장에는 tf.train.Saver 를 사용한다
saver = tf.train.Saver()
# 실제 메모리와 코어를 사용할 세션을 생성
with tf.Session() as sess:
# 메모리에 등록하는 액션을 실제로 실행
result = sess.run(init_op)
# 더하기 연산 수행과 그 결과
result2 = sess.run(temp3)
print("result2 : " + str(result2))
#지정한 경로에 해당 세션의 모든 정보를 저장한다
save_path = saver.save(sess, "/tmp/model.ckpt")
print("Model saved in file: %s" % save_path)
if __name__ == '__main__':
tf.app.run()

나. 저장된 데이터의 복구
[chap2_restore_variables.py]
저장한 변수들을 로드하는 예제 , 실제로는 모델을 훈련하는 과정 후에 저장이 되었어야
하지만 모델을 훈련하는 과정은 생략되어 있음
# -*- coding: utf-8 -*-
import tensorflow as tf
def main(_):
# 저장할때와 마찬가지로 변수명 자체는 생성 필요 . 이니셜 값 자체는 동일해야 함
weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35),name="weights")
biases = tf.Variable(tf.zeros([200]), name="biases")
w2 = tf.Variable(weights.initialized_value(), name="w2")
w_twice = tf.Variable(weights.initialized_value() * 5.0, name="w_twice")
temp1 = tf.constant(0.0)
temp2 = tf.constant(0.0)
temp3 = tf.add(temp1, temp2)
# 값을 찍어 보면 탠소 플로우 베리어블 객체의 내용을 확인 가능
print("weight : " + str(weights.initialized_value()))
print("biases : " + str(biases.initialized_value()))
print("w2 : " + str(w2.initialized_value()))
print("w_twice : " + str(w_twice.initialized_value()))
print("temp1 : " + str(temp1))
print("temp2 : " + str(temp2))
print("temp3 : " + str(temp3))
#저장에는 tf.train.Saver 를 사용한다
saver = tf.train.Saver()
# 실제 메모리와 코어를 사용할 세션을 생성
with tf.Session() as sess:
#
saver.restore(sess, "/tmp/model.ckpt")
print("Model restored.")
# 값을 찍어 보면 탠소 플로우 베리어블 객체의 내용을 확인 가능
# 더하기 연산 수행과 그 결과
result2 = sess.run(temp3)
print("result2 : " + str(result2))
if __name__ == '__main__':
tf.app.run()

안녕하세요. 포스트 잘 봤습니다 ㅎㅎ
저는 모델을 트레이닝 시켜서 저장한 다음 그 모델을 다시 가져와 사용하고 싶은데요. 그러면 모델 트레이닝 시 사용했던 모든 변수를 가져와서 사용하는 곳에 생성해 주어야 하는 것 인가요?
http://wp.me/p7xrpI-9Q 에 보시면 contrib 패키지를 사용해서 간단하게 테스트를 한 예제가 있습니다
low level 로 Saver 를 사용해서 모델을 저장하고 읽어오는 부분은 조만간 정리해서 올리겠습니다.
감사합니다!^^