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

时间:2018-07-05 08:20:01

标签: python tensorflow keras generative-adversarial-network

这是我为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采用100噪声+ 384嵌入矩阵并生成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。任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

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'对象没有属性'_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)