Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何处理KerasTensor和Tensor?_Python_Tensorflow_Keras_Deep Learning_Autoencoder - Fatal编程技术网

Python 如何处理KerasTensor和Tensor?

Python 如何处理KerasTensor和Tensor?,python,tensorflow,keras,deep-learning,autoencoder,Python,Tensorflow,Keras,Deep Learning,Autoencoder,我正在尝试创建可变自动编码器,这意味着我需要自定义损失函数。问题是,在损失函数中,我有两种不同的损失——均方误差和散度。mse是张量,散度是KerasTensor(因为色散和μ,我从编码器中取出)。我会犯这样的错误: TypeError:无法将符号Keras输入/输出转换为numpy 数组。此错误可能表示您正在尝试传递符号 值设置为NumPy调用,这是不受支持的。或者,你可能正在尝试 将Keras符号输入/输出传递给不需要 注册分派,防止Keras自动转换 对函数模型中lambda层的API调用

我正在尝试创建可变自动编码器,这意味着我需要自定义损失函数。问题是,在损失函数中,我有两种不同的损失——均方误差和散度。mse是张量,散度是KerasTensor(因为色散和μ,我从编码器中取出)。我会犯这样的错误:

TypeError:无法将符号Keras输入/输出转换为numpy 数组。此错误可能表示您正在尝试传递符号 值设置为NumPy调用,这是不受支持的。或者,你可能正在尝试 将Keras符号输入/输出传递给不需要 注册分派,防止Keras自动转换 对函数模型中lambda层的API调用

这就是我的架构:

import tensorflow.keras as keras
from keras.layers import Input, Dense, Flatten, Reshape
from keras.layers import Conv2D, MaxPooling2D, UpSampling2D, Conv2DTranspose
from keras.models import Model
import tensorflow as tf
import keras.backend as K


encoded_dim = 2

class Sampling(keras.layers.Layer):
    """Uses (z_mean, z_log_var) to sample z, the vector encoding a digit."""

    def call(self, inputs):
        z_mean, z_log_var = inputs
        batch = tf.shape(z_mean)[0]
        dim = tf.shape(z_mean)[1]
        epsilon = K.random_normal(shape=(batch, dim))
        return z_mean + tf.exp(0.5 * z_log_var) * epsilon


img = Input((28,28,1), name='img')

x = Conv2D(32, (3,3), padding='same', activation='relu')(img)
x = MaxPooling2D()(x)
x = Conv2D(64, (3,3), padding='same', activation='relu')(x)
x = MaxPooling2D()(x)
x = Flatten()(x)
x = Dense(16, activation='relu')(x)
mu = Dense(encoded_dim, name='mu')(x)
sigma = Dense(encoded_dim, name='sigma')(x)
z = Sampling()([mu,sigma])
# print(mu)
xx = Input((encoded_dim,))

x = Dense(7*7*64, activation='relu')(xx)
x = Reshape((7,7,64))(x)

x = Conv2DTranspose(64, 3, activation="relu", strides=2, padding="same")(x)
x = Conv2DTranspose(32, 3, activation="relu", strides=2, padding="same")(x)

out = Conv2DTranspose(1, 3, activation="sigmoid", padding="same")(x)

encoder = Model(img,z, name='encoder')
decoder = Model(xx,out,name='decoder')

autoencoder = Model(img,decoder(encoder(img)),name='autoencoder')
损失函数:

def vae_loss(x, y):
    loss = tf.reduce_mean(K.square(x-y))
    kl_loss = -0.5 * tf.reduce_mean(1 + sigma - tf.square(mu) - tf.exp(sigma))
    print(type(loss))
    print(type(kl_loss))
    return loss + kl_loss

autoencoder.compile(optimizer='adam',
                    loss = vae_loss)

autoencoder.fit(train,train,
                epochs=1,
                batch_size=60,
                shuffle=True,
                verbose = 2)
损失和lk_损失的类型:

类“tensorflow.python.framework.ops.Tensor”

类“tensorflow.python.keras.engine.keras\u tensor.KerasTensor”


您需要将
mu
sigma
传递给损失函数<代码>vae_损耗现在接受4个输入:

def vae_loss(x, y, mu, sigma):
    loss = tf.reduce_mean(K.square(x-y))
    kl_loss = -0.5 * tf.reduce_mean(1 + sigma - tf.square(mu) - tf.exp(sigma))
    return loss + kl_loss
您只需使用
自动编码器即可在模型中使用它。添加\u loss

同样重要的是,
encoder
不仅返回
z
,还返回
mu
sigma

z, mu, sigma = encoder(img)
out = decoder(z)
autoencoder = Model(img, out, name='autoencoder')
autoencoder.add_loss(vae_loss(img, out, mu, sigma))  # <======= add_loss
autoencoder.compile(loss=None, optimizer='adam')
z,mu,sigma=编码器(img)
out=解码器(z)
自动编码器=型号(img,out,name='autoencoder')
自动编码器。添加损耗(vae损耗(img、out、mu、sigma))#