【问题标题】:Quantize the variable with slicing assignment in Tensorflow在 Tensorflow 中使用切片赋值量化变量
【发布时间】:2018-08-05 12:02:58
【问题描述】:

我只想对变量的某些区域进行量化。 更具体地说,我只想在卷积层的任何通道上执行。

这是二值化代码:

G = tf.get_default_graph()
def binarize(x):
    with G.gradient_override_map({"Sign": "Identity"}):
        E = tf.stop_gradient(tf.reduce_mean(tf.abs(x)))
        return tf.sign(x) * E

我想通过for循环对与索引对应的变量区域进行量化。这是我在这里找到的变量赋值(How to do slice assignment in Tensorflow):

v = tf.get_variable(name, shape, **kwargs)

for i in range(start_index, end_index):
    if i in index:
        with tf.control_dependencies([v[:,:,i,:].assign(binarize(v[:,:,i,:]))]):
            v = tf.identity(v)

不过,据我所知,变量一旦赋值,就被视为张量,不能再次赋值。

这是第一次赋值后的错误信息:

ValueError: Sliced assignment is only supported for variables

有没有其他方法可以解决这个问题?


为了更清楚的问题,我添加了一些打印功能。

v = tf.get_variable(name, shape, **kwargs)

for i in range(start_index, end_index):
    if i in index:
        print(v)
        print(type(v))
        with tf.control_dependencies([v[:,:,i,:].assign(binarize(v[:,:,i,:]))]):
            v = tf.identity(v)
            print(v)
            print(type(v))
            print("Done")

结果:

<tf.Variable 'conv2/weights:0' shape=(5, 5, 96, 256) dtype=float32_ref>
<class 'tensorflow.python.ops.variables.Variable'>
<Tensor("tower0/conv2/Identity:0", shape=(5, 5, 96, 256), dtype=float32, device=/device:CPU:0)
<class 'tensorflow.python.framework.ops.Tensor'>
Done
<Tensor("tower0/conv2/Identity:0", shape=(5, 5, 96, 256), dtype=float32, device=/device:CPU:0)
<class 'tensorflow.python.framework.ops.Tensor'>    

ValueError: Sliced assignment is only supported for variables

【问题讨论】:

    标签: variables tensorflow slice quantization


    【解决方案1】:

    我发现自己是正确的答案,我觉得我做了一些很傻的事情。

    我通过在二值化函数中创建一个虚拟张量解决了这个问题。虚拟张量是相同形状的张量,1 在所需的索引处,0 在不想要的索引处。通过将其相乘,我可以仅量化所需的变量区域。

    代码如下:

    def binarize(x):
        positive_dummy_tensor, negative_dummy_tensor = dummy_tensor(x)
        pos_x = tf.multiply(x, positive_dummy_tensor)
        neg_x = tf.multiply(x, negative_dummy_tensor)
        with G.gradient_override_map({"Sign": "Identity"}):
            E = tf.stop_gradient(tf.reduce_mean(tf.abs(x)))
            return tf.add(tf.multiply(tf.sign(pos_x), E), neg_x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 2016-03-17
      • 2019-06-02
      相关资源
      最近更新 更多