我正在尝试在 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 ]
我想要实现的目标可能吗?
谢谢。
最佳答案
这就是我要做的:
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]]
如果您可以忍受舍入误差...
关于python - 如何将逐元素舍入函数应用于 Keras Tensor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50079766/