将张量从 128,128,3 转换为 129,128,3,填充到该张量的 1,128,3 值稍后发生

Convert a tensor from 128,128,3 to 129,128,3 and the 1,128,3 values padded to that tensor happens later

这是我的 GAN 代码,其中正在初始化模型,一切正常,这里只显示与问题相关的代码:

z = Input(shape=(100+384,))
img = self.generator(z)
print("before: ",img)    #128x128x3 shape, dtype=tf.float32
temp = tf.get_variable("temp", [1, 128, 3],dtype=tf.float32)
img=tf.concat(img,temp)
print("after: ",img)    #error ValueError: Incompatible type conversion requested to type 'int32' for variable of type 'float32_ref'
valid = self.discriminator(img)
self.combined = Model(z, valid)

我要生成 128x128x3 图像,我想做的是将 129x128x3 图像提供给鉴别器,并在训练时将 1x128x3 文本嵌入矩阵与图像连接起来。但我必须在开始时指定张量的形状和每个模型(即 GEN 和 DISC)将获得的输入值。 Gen 采用 100noise+384embedding 矩阵并生成 128x128x3 图像,该图像再次被一些嵌入嵌入,即 1x128x3 并被馈送到 DISC。所以我的问题是这种方法是否正确?此外,如果它是正确的或有意义的,那么我如何在开始时指定所需的东西,这样它就不会给我错误,例如不兼容的形状,因为在开始时我必须添加这些行:-

    z = Input(shape=(100+384,))
    img = self.generator(z)    #128x128x3
    valid = self.discriminator(img)   #should be 129x128x3
    self.combined = Model(z, valid)

但是 img 是 128x128x3,后来在训练期间通过连接嵌入矩阵更改为 129x128x3。那么,如何通过填充或附加另一个张量或简单地重塑,将上面代码中的 "img" 从 128,128,3 更改为 129,128,3,这当然是不可能的。任何帮助将不胜感激。谢谢

tf.concat 的第一个参数应该是张量列表,而第二个参数是连接的轴。您可以按如下方式连接 imgtemp 张量:

import tensorflow as tf

img = tf.ones(shape=(128, 128, 3))
temp = tf.get_variable("temp", [1, 128, 3], dtype=tf.float32)
img = tf.concat([img, temp], axis=0)

with tf.Session() as sess:
    print(sess.run(tf.shape(img)))

更新: 这里有一个最小的例子来说明为什么会出现错误 "AttributeError: 'Tensor' object has no attribute '_keras_history'"。此错误会在以下代码段中弹出:

from keras.layers import Input, Lambda, Dense
from keras.models import Model
import tensorflow as tf

img = Input(shape=(128, 128, 3))  # Shape=(batch_size, 128, 128, 3)
temp = Input(shape=(1, 128, 3))  # Shape=(batch_size, 1, 128, 3)
concat = tf.concat([img, temp], axis=1)
print(concat.get_shape())
dense = Dense(1)(concat)
model = Model(inputs=[img, temp], outputs=dense)

发生这种情况是因为张量 concat 不是 Keras 张量,因此缺少一些典型的 Keras 张量属性(例如 _keras_history)。为了克服这个问题,需要将所有的TensorFlow张量封装成一个Keras Lambda layer:

from keras.layers import Input, Lambda, Dense
from keras.models import Model
import tensorflow as tf

img = Input(shape=(128, 128, 3))  # Shape=(batch_size, 128, 128, 3)
temp = Input(shape=(1, 128, 3))  # Shape=(batch_size, 1, 128, 3)
concat = Lambda(lambda x: tf.concat([x[0], x[1]], axis=1))([img, temp])
print(concat.get_shape())
dense = Dense(1)(concat)
model = Model(inputs=[img, temp], outputs=dense)