python - AttributeError: 'tuple' 对象没有属性 'ndims' ,同时使用tensorflow eager执行模式

标签 python tensorflow deep-learning attributeerror

我正在使用 tf eager 模式,并尝试创建一个 GAN 模型。为此,我创建了一个类,如下所示。我尝试专门发送数组,在 keras 问题中发现,但这也不起作用?

class vanillaGAN(tf.keras.Model):
    """Vanilla GAN"""
    def __init__(self, noise_dims, input_dims):
        """Define all layer used in network"""
        super(vanillaGAN, self).__init__()
        self.disc1 = tf.keras.layers.Dense(128, activation='relu')
        self.disc2 = tf.keras.layers.Dense(1)#, activation='sigmoid')

        self.gen1 = tf.keras.layers.Dense(128, activation='relu')
        self.gen2 = tf.keras.layers.Dense(784)#, activation='sigmoid')

    def gen_forward(self, x):
        """Forward Pass for Generator"""
        x = self.gen1(x)
        x = self.gen2(x)
        return x

    def dis_forward(self, x):
        """Forward Pass for Discriminator"""
        x = self.disc1(x)
        x = self.disc2(x)
        return x

现在,使用以下脚本:

def sample(batch_size, dims):
    return np.random.uniform(size=(batch_size, dims))

gan = vanillaGAN(noise_dims=40, input_dims=784)

noise = sample(32,40)
#gan.gen_forward(np.array(noise))
gan.gen_forward(noise)}

我收到以下错误

----------------------------------------------------------------------
AttributeError                       Traceback (most recent call last)
<ipython-input-43-11c01bb2233d> in <module>
      1 noise = sample(32,40)
----> 2 gan.gen_forward(np.array(noise))

<ipython-input-20-22ce18fda8ff> in gen_forward(self, x)
     12     def gen_forward(self, x):
     13         """Forward Pass for Generator"""
---> 14         x = self.gen1(x)
     15         x = self.gen2(x)
     16         return x

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
    728 
    729         # Check input assumptions set before layer building, e.g. input rank.
--> 730         self._assert_input_compatibility(inputs)
    731         if input_list and self._dtype is None:
    732           try:

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py in _assert_input_compatibility(self, inputs)
   1461           spec.min_ndim is not None or
   1462           spec.max_ndim is not None):
-> 1463         if x.shape.ndims is None:
   1464           raise ValueError('Input ' + str(input_index) + ' of layer ' +
   1465                            self.name + ' is incompatible with the layer: '

AttributeError: 'tuple' object has no attribute 'ndims'

如果有人可以帮忙,请帮忙。

最佳答案

请注意,模型输入应该是张量,因此运行模型如下:

gan = vanillaGAN(noise_dims=40, input_dims=784)

noise = sample(32,40)

# define the tensors
noise_tensor = tf.placeholder(tf.float32, shape=[32,40])
gen_output = gan.gen_forward(noise_tensor)
dis_output = gan.dis_forward(noise_tensor)

# define the initializer
# Ref: https://stackoverflow.com/questions/45139423/tensorflow-error-failedpeconditionerror-attempting-to-use-uninitialized-variab
init = tf.global_variables_initializer() 

# run the graph
with tf.Session() as sess:
    sess.run(init)

    gen_output = sess.run(gen_output, feed_dict = {noise_tensor:noise})
    dis_output = sess.run(dis_output, feed_dict = {noise_tensor:noise})

    print(gen_output.shape)
    print(dis_output.shape)

错误消息表明 numpy 数组没有属性 xxx.shape.ndims

实验:

  1. 通过noise.shape.ndims访问numpy数组的xxx.shape.ndims:

Traceback (most recent call last):

File "", line 1, in noise.shape.ndims

AttributeError: 'tuple' object has no attribute 'ndims'

  • 通过 noise_tensor.shape.ndims 访问张量的 xxx.shape.ndims:
  • 2

    关于python - AttributeError: 'tuple' 对象没有属性 'ndims' ,同时使用tensorflow eager执行模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54250552/

    相关文章:

    python - 如何在tensorflow/keras中使用常量滤波器执行卷积

    machine-learning - 神经网络 - 如何处理 IRIS 输入向量?

    tensorflow - 初始化 LSTM 隐藏状态 Tensorflow/Keras

    python - 获取BeautifulSoup中id为空的标签内容

    python - 如何从 kwargs 加载包含 ReferenceField 的 Mongoengine 文档

    python - 交通标志分类 - 分配形状为 [] 且类型为 float 的张量时的 OOM

    matlab - 一般数据集的数据增强技术?

    python - Azure 分析休息 API : 401 Unauthorized. "Authentication failed."

    python - 将输出转换为 pandas 数据框

    tensorflow - 如何使用 tensorflow 2.0 将图形写入 tensorboard?