在函数张量流

时间:2017-04-15 15:16:16

标签: python tensorflow

如何为函数内的tf变量赋值? 根据这里的link,它说你需要在tf张量上运行一个sess。我想在几次计算后更新函数内的tf变量。

示例:

def update(weights):
    value_1 = 0
    value_2 = 2
    ........... some code here ...........
    weights['layer_1'] = tf.multiply(weights['layer_1'],value_1)
    weights['layer_2'] = tf.multiply(weights['layer_2'],value_2)
    ............some code here.............

我无法执行上述代码。但是如何使用assign来使这段代码有效呢?

2 个答案:

答案 0 :(得分:0)

你必须使用assign,它取一个Tensor,它必须与原始Variable完全相同。如果您想拥有不同的形状,请使用validate_shape=False。但是您必须记住,您将在运行时获得实际更改,因此您将编码变量的行为而不分配值。 这是一个显示变量赋值变量的示例:

import tensorflow as tf

var = tf.Variable(tf.zeros((1, 3)))
new_v = tf.assign(var, tf.ones((5, 7)), validate_shape=False)

init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init_op)
    print sess.run([var])
    print sess.run([new_v])

对于您的特定示例,您可以尝试:

def update(weights):
    value_1 = tf.constant(0)
    value_2 = tf.constant(2)
    ........... some code here ...........
    weights['layer_1'] =  tf.assign(weights['layer_1'], tf.multiply(weights['layer_1'],value_1))
    weights['layer_2'] =  tf.assign(weights['layer_2'], tf.multiply(weights['layer_2'],value_2))
    ............some code here.............

答案 1 :(得分:0)

这对我有用 -

import tensorflow as tf  
import numpy as np  

# function to randomly initialize weights for a specific layer
def assign_var(layer_number):  
    weight_value = np.random.rand(5,3) # or any calculations you need
    weight_var = tf.get_variable('weights_layer_'+str(layer_number))
    return tf.assign(weight_var,weight_value)  

with tf.Session() as sess:
    sess.run(assign_var(1))
    sess.run(assign_var(2))

编辑上述代码的问题是 - 每次调用函数时它都会不断添加到图表中。

或者,我认为这应该更好。

import tensorflow as tf  
import numpy as np  

var_name = tf.placeholder(tf.string)
weight_value = tf.placeholder(tf.float32)
weight_var = tf.get_variable(var_name)
assign_weights = tf.assign(weight_var,weight_value)  

sess = tf.Session()
# function to randomly initialize weights for a specific layer
def assign_var(layer_number):  
    rand_weight_value = np.random.rand(5,3) # or any calculations you need
    sess.run(assign_weights,{var_name:'weights_layer'+str(layer_number),weight_value:rand_weight_value})


assign_var(1) # assigns random weight values to layer 1