TensorFlow에서 Variable과 get_variable의 차이점
내가 아는 한, Variable
변수를 만들기위한 기본 작업 get_variable
이며 주로 가중치 공유에 사용됩니다.
한편 으로 변수가 필요할 때마다 get_variable
원시 Variable
작업 대신 사용 을 제안하는 사람들이 있습니다 . 반면에, 나는 단지 get_variable
TensorFlow의 공식 문서와 데모에서 사용 된 것을 본 것 입니다.
따라서이 두 메커니즘을 올바르게 사용하는 방법에 대한 몇 가지 규칙을 알고 싶습니다. "표준"원칙이 있습니까?
항상 사용하는 것이 좋습니다 tf.get_variable(...)
. 멀티 GPU 설정과 같이 언제든지 변수를 공유 해야하는 경우 코드를 쉽게 리팩터링하는 것이 더 쉬워집니다 (멀티 GPU CIFAR 예 참조). 단점은 없습니다.
순수한 tf.Variable
수준은 낮습니다. 어떤 시점 tf.get_variable()
에는 존재하지 않았으므로 일부 코드는 여전히 저수준 방식을 사용합니다.
tf.Variable은 클래스이며 tf.Variable .__ init__ 및 tf.get_variable을 포함하여 tf.Variable을 작성하는 몇 가지 방법이 있습니다.
tf.Variable .__ init__ : initial_value 로 새 변수를 작성 합니다.
W = tf.Variable(<initial-value>, name=<optional-name>)
tf.get_variable :이 매개 변수를 사용하여 기존 변수를 가져 오거나 새 변수를 만듭니다. 이니셜 라이저를 사용할 수도 있습니다.
W = tf.get_variable(name, shape=None, dtype=tf.float32, initializer=None,
regularizer=None, trainable=True, collections=None)
xavier_initializer와 같은 이니셜 라이저를 사용하는 것이 매우 유용합니다.
W = tf.get_variable("W", shape=[784, 256],
initializer=tf.contrib.layers.xavier_initializer())
자세한 내용은 https://www.tensorflow.org/versions/r0.8/api_docs/python/state_ops.html#Variable 에서 확인하십시오 .
하나와 다른 것의 두 가지 주요 차이점을 찾을 수 있습니다.
첫 번째는
tf.Variable
항상 새로운 변수를 만드는 반면 그래프에서 지정된 매개 변수를 가진 기존 변수를tf.get_variable
가져오고 존재하지 않는 경우 새 변수를 만듭니다.tf.Variable
초기 값을 지정해야합니다.
tf.get_variable
재사용 검사를 수행 하기 위해 함수 에 이름 앞에 현재 변수 범위가 붙는 것을 명확히하는 것이 중요 합니다. 예를 들면 다음과 같습니다.
with tf.variable_scope("one"):
a = tf.get_variable("v", [1]) #a.name == "one/v:0"
with tf.variable_scope("one"):
b = tf.get_variable("v", [1]) #ValueError: Variable one/v already exists
with tf.variable_scope("one", reuse = True):
c = tf.get_variable("v", [1]) #c.name == "one/v:0"
with tf.variable_scope("two"):
d = tf.get_variable("v", [1]) #d.name == "two/v:0"
e = tf.Variable(1, name = "v", expected_shape = [1]) #e.name == "two/v_1:0"
assert(a is c) #Assertion is true, they refer to the same object.
assert(a is d) #AssertionError: they are different objects
assert(d is e) #AssertionError: they are different objects
마지막 어설 션 오류는 흥미 롭습니다. 같은 범위에서 같은 이름을 가진 두 개의 변수는 같은 변수로 간주됩니다. 당신은 변수의 이름을 테스트한다면 d
그리고 e
당신은 알게 될 것이다 Tensorflow은 변수의 이름을 변경하는 것이 e
:
d.name #d.name == "two/v:0"
e.name #e.name == "two/v_1:0"
또 다른 차이점은 하나는 ('variable_store',)
수집에 있지만 다른 하나는 그렇지 않다는 것입니다.
소스 코드를 참조하십시오 :
def _get_default_variable_store():
store = ops.get_collection(_VARSTORE_KEY)
if store:
return store[0]
store = _VariableStore()
ops.add_to_collection(_VARSTORE_KEY, store)
return store
설명해 드리겠습니다 :
import tensorflow as tf
from tensorflow.python.framework import ops
embedding_1 = tf.Variable(tf.constant(1.0, shape=[30522, 1024]), name="word_embeddings_1", dtype=tf.float32)
embedding_2 = tf.get_variable("word_embeddings_2", shape=[30522, 1024])
graph = tf.get_default_graph()
collections = graph.collections
for c in collections:
stores = ops.get_collection(c)
print('collection %s: ' % str(c))
for k, store in enumerate(stores):
try:
print('\t%d: %s' % (k, str(store._vars)))
except:
print('\t%d: %s' % (k, str(store)))
print('')
출력 :
collection ('__variable_store',): 0: {'word_embeddings_2': <tf.Variable 'word_embeddings_2:0' shape=(30522, 1024) dtype=float32_ref>}
'program tip' 카테고리의 다른 글
빠르고 반응이 빠른 대화식 차트 / 그래프 : SVG, Canvas, 기타? (0) | 2020.07.27 |
---|---|
NSObject +로드 및 + 초기화-어떻게합니까? (0) | 2020.07.27 |
파이썬으로 mp3 메타 데이터 접근하기 (0) | 2020.07.27 |
R은 여러 매개 변수를 가진 기능을 적용 (0) | 2020.07.27 |
변화와 새 메시지를 전하지 않는 방법? (0) | 2020.07.27 |