我正在尝试使用急切执行。
我创建了一个训练集、一个权重和一个卷积层。
我声明卷积并更改权重。
如何在无需再次声明图层的情况下再次计算卷积?
我预计它会是这样的:
import tensorflow as tf
tf.enable_eager_execution()
tfe = tf.contrib.eager
TrainingDataExample = tf.constant(0.5, shape=[8, 5, 6, 1], name="Inputs")
WeightExample = tfe.Variable(tf.truncated_normal([1, 3, 1, 4], seed=1), name="Weights")
ConvExample = tf.nn.conv2d(TrainingDataExample, WeightExample, strides=[1, 1, 1, 1], padding="VALID", name="Conv")
NewWeightExample = tf.constant(2.0, shape=[1, 3, 1, 4], name="NewWeights")
WeightExample = tf.assign(WeightExample, NewWeightExample )
result = ConvExample
print (result)
但是不行,卷积的值没有更新。
我该怎么做?
最佳答案
我不太明白你所说的“无需再次声明图层”是什么意思。
方法tf.nn.conv2d
计算二维卷积。这就是如何使用 TensorFlow 计算卷积。
现在,您之前评估了 TrainingDataExample
上的卷积并将其存储在ConvExample
中。通过生成一组新的权重,NewWeightExample
并将其分配给覆盖变量 WeightExample
,它不会自动改变之前计算的卷积值ConvExample
.
因此,您将必须使用新的权重集再次重新计算卷积。您只需重新运行即可做到这一点:
ConvExample = tf.nn.conv2d(TrainingDataExample, WeightExample,
strides=[1, 1, 1, 1], padding="VALID",
name="Conv")
得到以下结果:
<tf.Tensor: id=36, shape=(8, 5, 4, 4), dtype=float32, numpy=
array([[[[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]],
...
关于python - 通过立即执行重新计算卷积值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52091047/