VAE 模型问题 - KerasTensor 与 TensorFlow 函数不兼容

问题描述 投票:0回答:1

Spark版本3.4.0 Python 3.9.16 张量流2.17.0

嗨,

我在使用以下配置构建 VAE(变分自动编码器)模型时遇到了问题:我正在将这项工作作为欺诈数据插补的一部分

Input dimension: 250
Latent dimension: 32

方法名称:build_vae_model 在 impute_data_vae 模块内调用 build_vae_model 时出现此错误,导致失败,错误描述如下:

错误:

A KerasTensor cannot be used as input to a TensorFlow function. A KerasTensor is a symbolic placeholder for a shape and dtype, used when constructing Keras Functional models or Keras Functions. You can only use it as input to a Keras layer or a Keras operation (from the namespaces `keras.layers` and `keras.operations`). You are likely doing something like:

```

x = Input(...)

...

tf_fn(x)  # Invalid.

```

What you should do instead is wrap `tf_fn` in a layer:

```
class MyLayer(Layer):

    def call(self, x):

        return tf_fn(x)
x = MyLayer()(x)
```

下一步,我将调整 build_vae_model 方法,将 TensorFlow 函数包装在适当的 Keras 层中。它变得非常耗时。如果有人遇到过类似的问题或对处理的最佳实践有建议,我将不胜感激。

谢谢

进一步调查

该错误是由于直接将 TensorFlow 操作(tf.shape 和 tf.random.normal)应用于 Keras 张量(z_mean、z_log_var)而引起的,而 Keras 不允许这样做。正如错误消息所示,解决方案是将这些操作封装在 Keras 层中。我实现了一个自定义采样层,如下所示:

from tensorflow.keras.layers import Layer

class Sampling(Layer):
    def call(self, inputs):
        z_mean, z_log_var = inputs
        batch = tf.shape(z_mean)[0]
        dim = tf.shape(z_mean)[1]
        epsilon = tf.random.normal(shape=(batch, dim))
        return z_mean + tf.exp(0.5 * z_log_var) * epsilon

然后我将这一层集成到 VAE 模型中以执行采样。这种方法解决了错误,因为它确保操作是 Keras 模型管道的一部分。

感谢您的意见。它有助于澄清此调整的必要性!

python tensorflow apache-spark
1个回答
0
投票

已经解决了。参见正文“进一步调查”下的解释

© www.soinside.com 2019 - 2024. All rights reserved.