我正在尝试对输入张量应用两种不同的掩蔽方法,一种是半正态分布滤波器,另一种是简单的阶跃函数。
虽然半高斯滤波器工作正常,但在尝试应用阶跃函数滤波器时,变量(即定义阶跃发生的点)似乎根本无法学习。
这是过滤器代码:
def per_kernel_step_filter(input,weight_param=20,trainable=True):
input_shape = input.get_shape().as_list()
weight_param_v = tf.Variable(np.full((input_shape[-1]),weight_param), dtype=tf.float32, trainable=trainable)
weight_param_v_c = tf.clip_by_value(weight_param_v, 0, input_shape[-2])
kernel_filter = tf.transpose(tf.sequence_mask(weight_param_v_c, input_shape[-2], dtype=tf.float32))
kernel_filter = tf.reshape(kernel_filter,tf.concat([(1,1),kernel_filter.get_shape()],0))
output = input * kernel_filter
tf.summary.histogram("weight_param histogram", weight_param_v)
return output
而且从 tensorboard 看来它最后甚至没有附加到 Adam 优化器。
并且 weight_param_v
在 weight_param
上持平。
是否有可能因为其他操作,例如 sequence_mask
变量变得不可训练?
最佳答案
这种情况下的问题是 tf.sequence_mask
是不可微分的,也就是说,如果您对 weight_param_v
应用小的更改,则没有分析函数可以告诉您输出(或损失)的变化有多大。一种可能的解决方法是改用一些 sigmoid或 smoothstep代替功能。例如,您可以使用 logistic function ( tf.math.sigmoid
),移动使其以步进点为中心,您可以操纵评估它的点以控制它的“陡峭”程度(注意这会影响梯度,进而影响变量的能力学习)。
一般来说,你可以使用tf.gradients
检查某些东西是否可区分。例如,如果你有一个函数 my_function
,你可以输入 x
并定义 y = my_function(x)
,然后检查输出tf.gradients(y, x)
;如果是[None]
,那么这个函数是不可微的。
import tensorflow as tf
x = tf.placeholder(tf.float32, [None])
# Squaring is differentiable
print(tf.gradients(tf.square(x), x))
# [<tf.Tensor 'gradients/Square_grad/Mul_1:0' shape=(?,) dtype=float32>]
# Flooring is not differentiable
print(tf.gradients(tf.floor(x), x))
# [None]
# Sequence mask is not differentiable
print(tf.gradients(tf.sequence_mask(x, dtype=tf.float32), x))
# [None]
# Gather is differentiable for the parameters but not for the indices
x2 = tf.placeholder(tf.int32, [None])
print(tf.gradients(tf.gather(x, x2), [x, x2]))
# [<tensorflow.python.framework.ops.IndexedSlices object at 0x000001F6EDD09160>, None]
一个棘手的事情,我认为这就是你在这种情况下发生的事情,即即使有一些 None
梯度,训练也可能有效。只要存在一些有效的梯度,TensorFlow(或者更具体地说,tf.train.Optimizer
及其子类)就假定 None
梯度是无关紧要的。您可以做的一项可能检查是,而不是调用 minimize
直接调用compute_gradients
并在调用 apply_gradients
之前检查没有 None
渐变.
关于python - Tensorflow - 可训练变量不随时间变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55242278/