如何将元素舍入函数应用于Keras张量?

2024-06-06 18:56:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Keras编写一个Lambda样式的层,它将前1D密集层(output_ulen)中的每个权重量化到最近的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)

例如,这个预测的结果是:

^{pr2}$

我要达到的目标是可能的吗?在

谢谢。在


Tags: lambda函数mapoutputbasetf样式precision
1条回答
网友
1楼 · 发布于 2024-06-06 18:56:24

我会这样做:

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]]

如果你能忍受舍入误差。。。在

相关问题 更多 >