【问题标题】:How to apply element-wise rounding function to Keras Tensor?如何将逐元素舍入函数应用于 Keras 张量?
【发布时间】:2018-04-28 18:25:40
【问题描述】:

我正在尝试在 Keras 中编写一个 Lambda 样式的层,将之前的 1D Dense(output_len) 层中的每个权重量化到最近的 1/128 步长。

我曾尝试在 Keras 后端使用 map_tf 函数,但到目前为止我没有运气。

基本上我想要做的是将以下函数元素应用于一维输入张量:

def quantize(x):
    'Squashes x (0->1) to steps of 1/128'
    precision = 3
    base = 0.0078125 # 1/128
    if x < 0:
        x = 0
    elif x > 1:
        x = 1

    return round(base * round(float(x)/base) - 1/256, precision)

因此,例如,这将是某个预测的结果:

input (after going through the CNN):
  [0.21940812, 0.7998919 , 0.5420448 , 0.33850232 ]
output (after leaving the quantization layer):
  [0.215, 0.793, 0.535, 0.332 ]

我正在努力实现的目标可能吗?

谢谢。

【问题讨论】:

    标签: python tensorflow deep-learning keras


    【解决方案1】:

    我会这样做:

    import tensorflow as tf
    from keras.models import Model
    from keras.layers import Input, Lambda
    import keras.backend as K
    import numpy as np
    
    def quantize(x):
        'Squashes x (0->1) to steps of 1/128'
        precision = 3
        base = 0.0078125 # 1/128
        x = K.clip( x, min_value = 0.0, max_value = 1.0 )
        return K.round( 1000 * ( base * K.round( x / base ) - 1.0 / 256 ) ) / 1000
    
    a = Input( shape = ( 4, ) )
    b = Lambda( quantize )( a )
    model = Model( inputs = a, outputs = b )
    print ( model.predict( np.array( [ [0.21940812, 0.7998919 , 0.5420448 , 0.33850232 ] ] ) ) )
    

    输出:

    [[0.215 0.79300004 0.535 0.33200002]]

    如果你能忍受舍入误差...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 2017-11-10
      • 2021-02-16
      • 1970-01-01
      相关资源
      最近更新 更多