如何更改 TensorFlow 中不是 tf.Variable 的张量的值?

How to change the value of a tensor which is not a tf.Variable in TensorFlow?

我知道TensorFlow中有一个tf.assign函数,但是这个函数主要针对可变张量(tf.Variable)。如何修改张量的值?比如下面的代码,

import numpy as np
import tensorflow as tf

X = tf.placeholder(tf.float32, shape=[None, 32, 32, 3])

conv1 = tf.layers.conv2d(X, filters=64, kernel_size=(3, 3), padding='same',name='conv1')
relu1 = tf.nn.relu(conv1)

conv2 = tf.layers.conv2d(relu1, filters=64, kernel_size=(3, 3), padding='same',name='conv2')
relu2 = tf.nn.relu(conv2)

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

tensor = sess.graph.get_tensor_by_name(u'conv2/Conv2D:0')
feature_map = tf.reduce_mean(tensor[:,:,:,24])

image = np.random.uniform(size=(1,32,32,3))
sess.run([feature_map], feed_dict={X: image})

如何修改feature_map的值并且不影响其推导?

更具体地说,当我改变feature_map的值时,并不影响它的推导过程。 比如y = a^2y'= 2a,我只要把a = 1改成a = 2就可以了。

Other_op = tf.gradients(feature_map, X)

不同的feature_map会得到不同的值,但不会破坏运算的图结构

这不可能。张量是 tf.Operation 的输出。来自 documentation:

A Tensor is a symbolic handle to one of the outputs of an Operation. It does not hold the values of that operation's output, but instead provides a means of computing those values in a TensorFlow tf.Session.

所以你不能单独改变它的值。

在您的示例中,feature_map 没有值,因为它是一个操作。因此你不能改变它的价值。您可以做的是将另一个值作为 session.run.

feed_dict 参数的一部分传递

例如,如果您的 feature_map 后跟这样的操作:

other_op = tf.gradient(feature_map, X)

然后您可以通过 feed_dict 更改传递给该操作的值(在本例中为 gradient),如下所示:

session.run(other_op, feed_dict={feature_map: <new value>})