我正在尝试将字符串(我从 JSON 中读取)转换为可由 Keras 层使用的参数。但是,当我发现 eval 函数创建的所有正则化对象都是相同的时。
a = eval('l1(0.1)')
b = eval('l2(0.1)')
c = eval('l1_l2(0.1)')
print(a,b,c)
给出:
<tensorflow.python.keras.regularizers.L1L2 object at 0x0000013F003C2F60>
<tensorflow.python.keras.regularizers.L1L2 object at 0x0000013F003C2D68>
<tensorflow.python.keras.regularizers.L1L2 object at 0x0000013F0032F160>
不应 eval('l1(0.1)') 给出
<function tensorflow.python.keras.regularizers.l1(l=0.01)>
任何关于为什么会发生这种情况的想法将不胜感激。
最佳答案
L1L2
同时存储l1
和l2
;在正则化器上运行,例如:
print(model.layers[1].kernel_regularizer.__dict__)
# {'l1': array(0., dtype=float32), 'l2': array(1., dtype=float32)}
要访问其中之一:
print(model.layers[1].kernel_regularizer.l1) # 0.0
print(model.layers[1].kernel_regularizer.l2) # 1.0
在您的代码中,a
设置 l1
、b
设置 l2
和 c
设置两者。
from keras.layers import Input, Dense
from keras.regularizers import l2
from keras.models import Model
ipt = Input(shape=(100,4))
x = Dense(10, activation='relu', kernel_regularizer=l2(1))(ipt)
out = Dense(1, activation='sigmoid')(x)
model = Model(ipt, out)
model.compile(optimizer='adam', loss='binary_crossentropy')
print(model.layers[1].kernel_regularizer.__dict__)
print(model.layers[1].kernel_regularizer.l1)
print(model.layers[1].kernel_regularizer.l2)
关于python - 为什么 Python eval 为 Keras 正则化器返回相同的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58206062/