如何使用keras将标量值添加到自动编码器中的潜在变量中
How to add scalar value into latent variables in auto-encoder with keras
我尝试将一个特定的标量值(0 到 1;每个图像都有)输入到一层潜在变量中。
如何在基于 CNN 的自动编码器序列模型中插入值?
def encoder():
model = tf.keras.Sequential()
model.add(Conv2D(12, (2,2), activation='relu', padding='same', input_shape=(32, 32, 1)))
model.add(MaxPooling2D(pool_size=(2, 2), padding='same'))
model.add(Flatten())
model.add(Dense(64))
return model
# maybe some code here
def decoder():
model = tf.keras.Sequential()
model.add(Dense(16*16*12, input_shape=(65,)))
model.add(Reshape((16,16,12)))
model.add(Conv2D(32, (2, 2), activation='relu', padding='same'))
model.add(UpSampling2D((2, 2)))
model.add(Dropout(0.5))
model.add(Conv2D(1, (2, 2), padding='same'))
return model
编码器中的隐变量个数为64,因此一个标量变量在解码器中应该有65个隐变量。
可以应用连接层吗?
您可以为此使用 Concatenate layer。
例如:
x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2))
x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2))
concatted = tf.keras.layers.Concatenate()([x1, x2])
但是您必须为要添加的常量选择正确的 shape
。
对于你的情况,你可以使用:
...
outputs = tf.keras.layers.Concatenate()([model, your_constant])
model = tf.keras.Model(inputs=model.inputs, outputs=outputs)
return model
...
这个解决方案对你有用吗?
我尝试将一个特定的标量值(0 到 1;每个图像都有)输入到一层潜在变量中。 如何在基于 CNN 的自动编码器序列模型中插入值?
def encoder():
model = tf.keras.Sequential()
model.add(Conv2D(12, (2,2), activation='relu', padding='same', input_shape=(32, 32, 1)))
model.add(MaxPooling2D(pool_size=(2, 2), padding='same'))
model.add(Flatten())
model.add(Dense(64))
return model
# maybe some code here
def decoder():
model = tf.keras.Sequential()
model.add(Dense(16*16*12, input_shape=(65,)))
model.add(Reshape((16,16,12)))
model.add(Conv2D(32, (2, 2), activation='relu', padding='same'))
model.add(UpSampling2D((2, 2)))
model.add(Dropout(0.5))
model.add(Conv2D(1, (2, 2), padding='same'))
return model
编码器中的隐变量个数为64,因此一个标量变量在解码器中应该有65个隐变量。 可以应用连接层吗?
您可以为此使用 Concatenate layer。 例如:
x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2))
x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2))
concatted = tf.keras.layers.Concatenate()([x1, x2])
但是您必须为要添加的常量选择正确的 shape
。
对于你的情况,你可以使用:
...
outputs = tf.keras.layers.Concatenate()([model, your_constant])
model = tf.keras.Model(inputs=model.inputs, outputs=outputs)
return model
...
这个解决方案对你有用吗?