重用张量流变量



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

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

你可以尝试这样的事情:

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())

我希望这有帮助!

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

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

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操作。它将选取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_testx_ph,它只会计算y_pred = x_ph * W + b(将Wb作为常量),而不修改任何其他内容。

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

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

fixW = tf.assign(W, [-1., 1.])
fixb = tf.assign(b, [1.])
sess.run([fixW, fixb])
print(sess.run(loss, {x_ph:x_test}))

最新更新