我尝试从教程运行此代码:
from keras.layers import Input, Dense
from keras.layers import BatchNormalization, Dropout, Flatten, Reshape, Lambda
from keras.models import Model
from keras.objectives import binary_crossentropy
from keras.layers.advanced_activations import LeakyReLU
from keras import backend as K
def create_vae():
models = {}
# Добавим Dropout и BatchNormalization
def apply_bn_and_dropout(x):
return Dropout(dropout_rate)(BatchNormalization()(x))
# Энкодер
input_img = Input(batch_shape=(batch_size, 28, 28, 1))
x = Flatten()(input_img)
x = Dense(256, activation='relu')(x)
x = apply_bn_and_dropout(x)
x = Dense(128, activation='relu')(x)
x = apply_bn_and_dropout(x)
# Предсказываем параметры распределений
# Вместо того, чтобы предсказывать стандартное отклонение, предсказываем логарифм вариации
z_mean = Dense(latent_dim)(x)
z_log_var = Dense(latent_dim)(x)
# Сэмплирование из Q с трюком репараметризации
def sampling(args):
z_mean, z_log_var = args
epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0., stddev=1.0)
return z_mean + K.exp(z_log_var / 2) * epsilon
l = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])
models["encoder"] = Model(input_img, l, 'Encoder')
models["z_meaner"] = Model(input_img, z_mean, 'Enc_z_mean')
models["z_lvarer"] = Model(input_img, z_log_var, 'Enc_z_log_var')
# Декодер
z = Input(shape=(latent_dim, ))
x = Dense(128)(z)
x = LeakyReLU()(x)
x = apply_bn_and_dropout(x)
x = Dense(256)(x)
x = LeakyReLU()(x)
x = apply_bn_and_dropout(x)
x = Dense(28*28, activation='sigmoid')(x)
decoded = Reshape((28, 28, 1))(x)
models["decoder"] = Model(z, decoded, name='Decoder')
models["vae"] = Model(input_img, models["decoder"](models["encoder"](input_img)), name="VAE")
def vae_loss(x, decoded):
x = K.reshape(x, shape=(batch_size, 28*28))
decoded = K.reshape(decoded, shape=(batch_size, 28*28))
xent_loss = 28*28*binary_crossentropy(x, decoded)
kl_loss = -0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
return (xent_loss + kl_loss)/2/28/28
return models, vae_loss
models, vae_loss = create_vae()
vae = models["vae"]
但是Colab向我展示了一个错误,怎么了?
AttributeError Traceback (most recent call last)
<ipython-input-108-b96af0c31b2f> in <module>()
61 return models, vae_loss
62
---> 63 models, vae_loss = create_vae()
64 vae = models["vae"]
2 frames
/usr/local/lib/python3.6/dist-packages/keras/engine/network.py in call(self, inputs, mask)
559 cache_key = object_list_uid(inputs)
560 cache_key += '_' + object_list_uid(masks)
--> 561 if cache_key in self._output_tensor_cache:
562 return self._output_tensor_cache[cache_key]
563 else:
AttributeError: 'Model' object has no attribute '_output_tensor_cache'
我正在尝试研究VAE,无法找到如何解决该问题。该行生成错误:
models["vae"] = Model(input_img, models["decoder"](models["encoder"](input_img)), name="VAE")
,但对我来说看起来完全不错。不要阅读我在下面写的内容,这个网站不允许我没有额外的文字发布问题:看来您的帖子主要是代码;请添加更多详细信息。
一些相关讨论请参阅那里
随后在我的情况下有帮助(python 3.7
(:
pip install tensorflow==1.14.0
pip install keras==2.0