tensorflow TypeError:“KerasTensor”对象不可调用

8iwquhpp  于 2023-04-12  发布在  其他
关注(0)|答案(1)|浏览(176)

此代码使用变分自动编码器生成合成HVAC数据(VAE)模型。VAE是在原始HVAC数据上训练的,并且训练后的VAE用于生成类似于原始数据的合成数据。然而,我得到了这个错误,我不知道为什么,下面是有问题的代码段。错误发生在vae_output = MyModel行(input_shape)(inputs=vae_input).有人可以帮助这个吗??谢谢

import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
import joblib
import os
from keras.callbacks import EarlyStopping
from keras.losses import mse
from keras.layers import Input, Dense, Dropout
from keras.layers import Lambda
from keras import backend as K
from keras.models import Model
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
from tensorflow import keras

data_initial = pd.read_excel('hvac.xlsx', header=None)

data = data_initial.iloc[0:96,0:3]

# Define the number of samples to generate
n_samples = 1000


class CastLayer(keras.layers.Layer):
    def __init__(self, output_type='float32', **kwargs):
        self.output_type = output_type
        super(CastLayer, self).__init__(**kwargs)

    def call(self, inputs):
        return tf.cast(inputs, self.output_type)

    def compute_output_shape(self, input_shape):
        return input_shape

# Define the VAE model
original_dim = 3
input_shape = (original_dim,)
intermediate_dim = 512
batch_size = 1
latent_dim = 10
epochs = 10000

x = Input(shape=input_shape)
h = Dense(intermediate_dim, activation='relu')(x)
h = Dropout(0.2)(h)
z_mean = Dense(latent_dim)(h)
z_log_var = Dense(latent_dim)(h)

def sampling(args):
    z_mean, z_log_var = args
    epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0., stddev=1.)
    return z_mean + K.exp(z_log_var / 2) * epsilon

z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])

decoder_h = Dense(intermediate_dim, activation='relu')

decoder_mean = Dense(original_dim, activation='linear', input_shape=(intermediate_dim,))

h_decoded = decoder_h(z)
x_decoded_mean = decoder_mean(h_decoded)

decoder_inputs = Input(shape=(latent_dim,))
decoder_h_decoded = decoder_h(decoder_inputs)
x_decoded_mean = decoder_mean(decoder_h_decoded)
decoder = Model(decoder_inputs, x_decoded_mean)

def MyModel(input_shape):
    inputs = Input(shape=input_shape)
    x = Dense(256, activation='relu')(inputs)
    x = Dense(128, activation='relu')(x)
    outputs = Dense(original_dim, activation='linear')(x)
    return outputs

vae_input = Input(shape=input_shape)
vae_output = MyModel(input_shape)(inputs=vae_input) # replace YourModel with the actual name of your model
cast_layer = tf.keras.layers.Lambda(lambda x: tf.cast(x, tf.float32))(vae_output)
vae = Model(vae_input, vae_output)
ryevplcw

ryevplcw1#

Meh,在那个函数(MyModel)中,返回的是输出而不是模型。所以它只是一个Tensor,你不能调用它。
你应该这样做:

def get_output(inputs):
    x = Dense(256, activation='relu')(inputs)
    x = Dense(128, activation='relu')(x)
    outputs = Dense(original_dim, activation='linear')(x)
    return outputs

vae_input = Input(shape=input_shape)
vae_output = get_output(vae_input)
....

相关问题