如何在 Tensorflow 中量化 tf.Variables 的值

How to quantize the values of tf.Variables in Tensorflow

我有一个像

这样的训练模型
Y = w * X + b

其中 Y 和 X 是输出和输入占位符,w 和 b 是向量
我已经知道w的值只能是0或者1,而b还是tf.float32.

定义变量w的范围怎么量化?

我可以有两个不同的学习率吗? w 的比率为 1 或 -1,b 的比率照常为 0.0001。

激活期间无法限制您的变量。但是您可以做的是在每次迭代后对其进行限制。这是使用 tf.where() 执行此操作的一种方法:

import tensorflow as tf

a = tf.random_uniform(shape=(3, 3))

b = tf.where(
    tf.less(a, tf.zeros_like(a) + 0.5),
    tf.zeros_like(a),
    tf.ones_like(a)
)

with tf.Session() as sess:
    A, B = sess.run([a, b])
    print A, '\n'
    print B

这会将大于 0.5 的所有值转换为 1,将其他所有值转换为 0:

[[ 0.2068541   0.12682056  0.73839438]
 [ 0.00512838  0.43465161  0.98486936]
 [ 0.32126224  0.29998791  0.31065524]] 

[[ 0.  0.  1.]
 [ 0.  0.  1.]
 [ 0.  0.  0.]]

我用来将变量限制在特定范围内的一种方法是在我的损失方程中添加一个约束。如果变量超出所需范围,则损失会变大,优化器会将其推回到所需范围内。

例如:

#initialize variable to be between 0 and 1
variable = tf.Variable(tf.random_uniform([self.numOutputs], 0, 1))

#Clip the variable to force the result to be between 0 and 1 during training
variableClipped = tf.clip_by_value(variable, 0, 1)

#Set the loss to be the difference between the clipped variable and actual variable.
#Anytime it goes outside the variable range the loss will increase,
#and the optimizer will push it back within the desired range.
loss =  originalLossEquation + tf.reduce_sum((variable - variableClipped)**2)