为 Keras 中的某些张量元素分配新值 [英] Assign new values to certain tensor elements in Keras

查看:25
本文介绍了为 Keras 中的某些张量元素分配新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更改张量的某些元素的值.我知道哪些元素——它们已经在一个布尔张量中.

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:

TensorFlow 中张量值的条件赋值

python numpy中,代码看起来像这样:

In python numpy, the code would look something like this:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆