developer tip

TensorFlow 변수에 값을 할당하는 방법은 무엇입니까?

optionbox 2020. 10. 26. 07:55
반응형

TensorFlow 변수에 값을 할당하는 방법은 무엇입니까?


파이썬에서 tensorflow 변수에 새 값을 할당하려고합니다.

import tensorflow as tf
import numpy as np

x = tf.Variable(0)
init = tf.initialize_all_variables()
sess = tf.InteractiveSession()
sess.run(init)

print(x.eval())

x.assign(1)
print(x.eval())

그러나 내가 얻는 출력은

0
0

따라서 값은 변경되지 않았습니다. 내가 무엇을 놓치고 있습니까?


이 명령문 x.assign(1)은 실제로에 값 1할당하는 x것이 아니라 변수를 업데이트 tf.Operation하기 위해 명시 적으로 실행 해야하는를 생성 합니다. * Operation.run()또는에 대한 호출을 Session.run()사용하여 작업을 실행할 수 있습니다.

assign_op = x.assign(1)
sess.run(assign_op)  # or `assign_op.op.run()`
print(x.eval())
# ==> 1

(* 실제로는 tf.Tensor할당을 더 쉽게 연결할 수 있도록 업데이트 된 변수 값에 해당 하는를 반환 합니다.)


tf.Variable그래프에 작업을 추가하지 않고에 새 값을 할당 할 수도 있습니다 tf.Variable.load(value, session).. 이 기능은 또한 그래프 외부에서 값을 할당 할 때 자리 표시자를 추가하는 것을 절약 할 수 있으며 그래프가 완성 된 경우에 유용합니다.

import tensorflow as tf
x = tf.Variable(0)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(x))  # Prints 0.
x.load(1, sess)
print(sess.run(x))  # Prints 1.

업데이트 : eager 실행이 기본값이고 그래프가 더 이상 사용자 용 API에 노출되지 않으므로 TF2에서는 더 이상 사용되지 않습니다 .


우선 자리 표시 자와 같은 방식으로 값을 입력하여 변수 / 상수에 값을 할당 할 수 있습니다. 따라서 이것은 완벽하게 합법적입니다.

import tensorflow as tf
x = tf.Variable(0)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print sess.run(x, feed_dict={x: 3})

tf.assign () 연산자 와의 혼동에 관해서 . TF에서는 세션 내에서 실행하기 전에 아무것도 실행되지 않습니다. 따라서 항상 다음과 같은 작업을 수행해야합니다. op_name = tf.some_function_that_create_op(params)그런 다음 세션 내에서 sess.run(op_name). 예를 들어 assign을 사용하면 다음과 같이 할 수 있습니다.

import tensorflow as tf
x = tf.Variable(0)
y = tf.assign(x, 1)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print sess.run(x)
    print sess.run(y)
    print sess.run(x)

또한, 당신이 사용하는 경우 주목해야한다 your_tensor.assign(), 다음 tf.global_variables_initializer할당 작업이 백그라운드에서 당신을 위해 그것을 않기 때문에 명시 적으로 호출 할 필요가 없습니다.

예:

In [212]: w = tf.Variable(12)
In [213]: w_new = w.assign(34)

In [214]: with tf.Session() as sess:
     ...:     sess.run(w_new)
     ...:     print(w_new.eval())

# output
34 

그러나 이것은 모든 변수를 초기화하는 것은 아니지만 assign실행 된 변수 만 초기화합니다 .


I answered a similar question here. I looked in a lot of places that always created the same problem. Basically, I did not want to assign a value to the weights, but simply change the weights. The short version of the above answer is:

tf.keras.backend.set_value(tf_var, numpy_weights)


Here is the complete working example:

import numpy as np
import tensorflow as tf

w= tf.Variable(0, dtype=tf.float32) #good practice to set the type of the variable
cost = 10 + 5*w + w*w
train = tf.train.GradientDescentOptimizer(0.01).minimize(cost)

init = tf.global_variables_initializer()
session = tf.Session()
session.run(init)

print(session.run(w))

session.run(train)
print(session.run(w)) # runs one step of gradient descent

for i in range(10000):
  session.run(train)

print(session.run(w))

Note the output will be:

0.0
-0.049999997
-2.499994

This means at the very start the Variable was 0, as defined, then after just one step of gradient decent the variable was -0.049999997, and after 10.000 more steps we are reaching -2.499994 (based on our cost function).

Note: You originally used the Interactive session. Interactive session is useful when multiple different sessions needed to be run in the same script. However, I used the non interactive session for simplicity.


Use Tensorflow eager execution mode which is latest.

import tensorflow as tf
tf.enable_eager_execution()
my_int_variable = tf.get_variable("my_int_variable", [1, 2, 3])
print(my_int_variable)

So i had a adifferent case where i needed to assign values before running a session, So this was the easiest way to do that:

other_variable = tf.get_variable("other_variable", dtype=tf.int32,
  initializer=tf.constant([23, 42]))

here i'm creating a variable as well as assigning it values at the same time


There is an easier approach:

x = tf.Variable(0)
x = x + 1
print x.eval()

참고URL : https://stackoverflow.com/questions/34220532/how-to-assign-a-value-to-a-tensorflow-variable

반응형