重用Tensorflow变量

时间:2017-06-08 01:00:19

标签: python tensorflow

根据我是在训练网络还是实际运行它,我想基本上有两个不同的图表。基本上,一件使用一些无监督技术来学习给定矩阵的值,然后我想在不同的图中使用完全相同的矩阵。

我知道如何使用matrix_value = sess.run(my_matrix, {input=input_data})获取矩阵的值,但是有没有办法用设定值初始化tf.Variable

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

import numpy as np
import tensorflow as tf

value = [0, 1, 2, 3, 4, 5, 6, 7]
init = tf.constant_initializer(value)

with tf.Session():
    x = tf.get_variable('x', shape=[2, 4], initializer=init)
    x.initializer.run()
    print(x.eval())

我希望这有帮助!

答案 1 :(得分:1)

您不必创建两个相同的图表,您可以使用相同但运行不同的节点。

让我解释一下我的意思。我们来看看这个例子:

W = tf.Variable(tf.truncated_normal([1, 1], stddev=0.1))
# Declare bias variable initialized to a constant 0.1
b = tf.Variable(tf.constant(0.1, shape=[1]))

y_pred = x_ph * W + b

# loss function
loss = tf.mul(tf.reduce_mean(tf.square(tf.sub(y_pred, y_ph))), 1. / 2)

第一部分调用train_op

train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

此操作将基于loss操作运行梯度下降步骤,这将导致更新变量Wb

with tf.Session() as sess:
    # initialize all the variables by running the initializer operator
    sess.run(init)
    for epoch in xrange(num_epoch):
        # Run sequentially the train_op and loss operators with
        # x_ph and y_ph placeholders fed by variables x and y
        _, loss_val = sess.run([train_op, loss], feed_dict={x_ph: x, y_ph: y})
        print('epoch %d: loss is %.4f' % (epoch, loss_val))

但是现在如果你只想运行它,你可以运行y_pred op。它将获取Wb的当前值,并且不会修改它们,因为您没有调用train_op

with tf.Session() as sess:
    # see what model do in the test set
    # by evaluating the y_pred operator using the x_test data
    test_val = sess.run(y_pred, feed_dict={x_ph: x_test})

当您要求TensorFlow运行操作y_pred并将新数据x_test输入x_ph时,它只会计算y_pred = x_ph * W + b(取W和{ {1}}为常数)而不修改任何其他内容。

此外,值得一提的是,当您完成训练后,您可以覆盖一些变量值(例如,在学习变量值非常接近1的情况下,您可以将其设置为1直接根据TensorFlow documentation

  

我们可以通过将W和b的值重新分配给-1和1的完美值来手动改进。变量初始化为提供给tf.Variable的值,但可以使用tf.assign等操作进行更改。例如,W = -1和b = 1是我们模型的最佳参数。我们可以相应地改变W和b:

b
相关问题