在Keras代码中:将新值分配给某些张量元素 [英] In Keras code: Assign new values to certain tensor elements
问题描述
我需要更改张量的某些元素的值.我知道什么元素-它们已经在布尔张量中.
I need to change the value of some elements of a tensor. I know what elements -- they are in a boolean tensor already.
我看不到如何在keras代码中做到这一点.但是,如果我使用TensorFlow代码,我会做这样的事情:
I don't see how to do this in keras code. But if I were using TensorFlow code I would do something like this:
在 python numpy 中,代码如下所示:
x = np.zeros_like(sometensor)
x[sometensor>0.5] = 1.0
在Keras代码中(并且我正在使用TF后端),这是我的最佳尝试(无效):
In Keras code (and I'm using TF backend) here's my best attempt (does not work):
encoder_outputs_bin = k.backend.zeros_like(encoder_outputs, name="encoder_outputs_bin")
point_five = k.backend.constant(0.5, shape=k.backend.shape(encoder_outputs), name="point_five")
positives = k.backend.greater_equal(encoder_outputs, point_five)
encoder_outputs_bin[positives].assign(tf.ones(1)) # TF syntax -- might not work in keras
推荐答案
激活中的lambda函数对我有用.比简单地使用内置的激活功能要复杂得多.
A lambda function in the activation worked for me. It is one step more complicated than the simple use of a built-in activation function.
encoder_outputs = Dense(units=latent_vector_len, activation=k.layers.Lambda(lambda z: k.backend.round(k.layers.activations.sigmoid(x=z))), kernel_initializer="lecun_normal")(x)
此代码将Dense的输出从Reals更改为0,1(即二进制).
This code changes the output of a Dense from Reals to 0,1 (ie, binary).
Keras发出警告,但代码仍然有效.
Keras throws a warning but the code still proves to work.
# Look it works!
y = encoder_model.predict(x=x_in)
print(y)
>>>[[1. 0. 0. 1. 0. 1. 0. 0.]]
这篇关于在Keras代码中:将新值分配给某些张量元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!