创建由两个子模型组成且使用函数式API创建的模型时,遇到“必须为占位符张量提供值”的错误

在实现变分自编码器时,我遇到了这个问题。以下是最小可复现示例,其中包含一个简单的encoderdecodervae,所有这些都是使用函数式API创建的。vae通常由encoderdecoder组成。我使用自定义回调来获取中间层预测结果。

import tensorflow as tfimport numpy as npinputs = tf.keras.layers.Input((1,))outputs = tf.keras.layers.Dense(units=32)(inputs)encoder = tf.keras.Model(inputs, outputs)    inputs = tf.keras.layers.Input((32,))outputs = tf.keras.layers.Dense(units=1)(inputs)decoder = tf.keras.Model(inputs, outputs)inputs = tf.keras.layers.Input((1,))x = encoder(inputs)outputs = decoder(x)vae = tf.keras.Model(inputs, outputs)class CustomCallback(tf.keras.callbacks.Callback):    def on_epoch_end(self, epoch, logs=None):        get_output = tf.keras.backend.function(            inputs = self.model.layers[0].input,            outputs = self.model.layers[1].output        )        print("\nPrediction:",get_output(X))X = np.random.random_sample((8,1))y = Xvae.compile(optimizer='adam', loss='mse')vae.fit(X, y, epochs=2, callbacks=[CustomCallback()])

运行上述代码时,我得到了以下错误:

<ipython-input-3-fd96ce817cad> in on_epoch_end(self, epoch, logs)      5             outputs = self.model.layers[1].output      6         )----> 7         print("\nPrediction:",get_output(X))..InvalidArgumentError:  You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,1]     [[node input_1 (defined at <ipython-input-3-fd96ce817cad>:5) ]] [Op:__inference_keras_scratch_graph_539]Function call stack:keras_scratch_graph

但是,当仅训练编码器时,如下所示:

X = np.random.random_sample((8,1))y = np.random.random_sample((8,32))encoder.compile(optimizer='adam', loss='mse')encoder.fit(X, y, epochs=2, callbacks=[CustomCallback()])

一切正常工作。

是什么导致了这个错误?如何修复它?


回答:

这里是正确定义它的方法

inp_enc = tf.keras.layers.Input((1,))out_enc = tf.keras.layers.Dense(units=32)(inp_enc)encoder = tf.keras.Model(inp_enc, out_enc)    out_dec = tf.keras.layers.Dense(units=1)(encoder.output)decoder = tf.keras.Model(encoder.input, out_dec)vae = tf.keras.Model(encoder.input, decoder.output)class CustomCallback(tf.keras.callbacks.Callback):        def on_epoch_end(self, epoch, logs=None):        get_output = tf.keras.backend.function(            inputs = self.model.layers[0].input,            outputs = self.model.layers[1].output        )        print("\nPrediction:", get_output(X))X = np.random.random_sample((8,1))y = Xvae.compile(optimizer='adam', loss='mse')vae.fit(X, y, epochs=2, callbacks=[CustomCallback()])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注