TypeError:“ Conv2DTranspose”类型的对象没有len()

时间:2019-07-31 18:56:59

标签: tensorflow keras

我正在使用Keras编码自动编码器,但不断出现以下错误。我认为这与添加arg keras_initializer有关,因为在Conv2D之前我遇到了此错误,因此添加了初始化程序并且Conv2D具有长度。虽然,由于我使用的是tf.keras.layers.reshape,所以这不是有效的参数。

这是整个错误回溯。

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-c8370b57aa14> in <module>()
     57 
     58 
---> 59 autoencoder = keras.Model(inputs = encoder_input, outputs = decoder_output, name='autoencoder')
     60 autoencoder.summary()
     61 

4 frames
/usr/local/lib/python3.6/dist-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
     89                 warnings.warn('Update your `' + object_name + '` call to the ' +
     90                               'Keras 2 API: ' + signature, stacklevel=2)
---> 91             return func(*args, **kwargs)
     92         wrapper._original_function = func
     93         return wrapper

/usr/local/lib/python3.6/dist-packages/keras/engine/network.py in __init__(self, *args, **kwargs)
     91                 'inputs' in kwargs and 'outputs' in kwargs):
     92             # Graph network
---> 93             self._init_graph_network(*args, **kwargs)
     94         else:
     95             # Subclassed network

/usr/local/lib/python3.6/dist-packages/keras/engine/network.py in _init_graph_network(self, inputs, outputs, name)
    229         # Keep track of the network's nodes and layers.
    230         nodes, nodes_by_depth, layers, layers_by_depth = _map_graph_network(
--> 231             self.inputs, self.outputs)
    232         self._network_nodes = nodes
    233         self._nodes_by_depth = nodes_by_depth

/usr/local/lib/python3.6/dist-packages/keras/engine/network.py in _map_graph_network(inputs, outputs)
   1364                   layer=layer,
   1365                   node_index=node_index,
-> 1366                   tensor_index=tensor_index)
   1367 
   1368     for node in reversed(nodes_in_decreasing_depth):

/usr/local/lib/python3.6/dist-packages/keras/engine/network.py in build_map(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
   1345 
   1346         # Propagate to all previous tensors connected to this node.
-> 1347         for i in range(len(node.inbound_layers)):
   1348             x = node.input_tensors[i]
   1349             layer = node.inbound_layers[i]

TypeError: object of type 'Conv2DTranspose' has no len()

这是我的代码:

import tensorflow as tf
import keras
import numpy as np 
import tensorflow.keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import cifar10
from keras.layers import Input, Conv2DTranspose
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
num_classes = 10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
num_classes = 10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
#plt.imshow(x_train[1])

encoder_input = tf.keras.layers.Input(shape=(32, 32, 3), name="input")
x = tf.keras.layers.Conv2D(16, 3,activation = 'relu', kernel_initializer = keras.initializers.RandomUniform)(encoder_input)
x = tf.keras.layers.Conv2D(32, 3, activation = 'relu')(x)
x = tf.keras.layers.MaxPooling2D(3)(x)
x = tf.keras.layers.Conv2D(32, 3,activation = 'relu')(x)
x = tf.keras.layers.Conv2D(16, 3, activation = 'relu')(x)
encoder_output = tf.keras.layers.GlobalMaxPooling2D()(x)

encoder = tf.keras.Model(inputs=encoder_input, outputs=encoder_output, name = 'encoder')
encoder.summary()

#Decoder
decoder_input = tf.keras.layers.Reshape((4, 4, 1))(encoder_output)
x = tf.keras.layers.Conv2DTranspose(16, 3, activation = 'relu')(decoder_input)
x = tf.keras.layers.Conv2DTranspose(32, 3, activation = 'relu')(x)
x = tf.keras.layers.UpSampling2D(3)(x)
x = tf.keras.layers.Conv2DTranspose(16, 3, activation = 'relu')(x)
decoder_output = tf.keras.layers.Conv2DTranspose(1, 3, activation = 'relu')(x)


autoencoder = keras.Model(inputs = encoder_input, outputs = decoder_output, name='autoencoder')
autoencoder.summary()


2 个答案:

答案 0 :(得分:2)

您正在混合tf.keraskeras的导入,并且不支持,并且该导入无效。您需要选择一种实现,并从中导入所有模块/类。

答案 1 :(得分:1)

在上述情况下,请使用from tensorflow import keras

更新的代码:

import tensorflow as tf
from tensorflow import keras

num_classes = 10
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')


encoder_input = tf.keras.layers.Input(shape=(32, 32, 3), name="input")
x = tf.keras.layers.Conv2D(16, 3,activation = 'relu', kernel_initializer = keras.initializers.RandomUniform)(encoder_input)
x = tf.keras.layers.Conv2D(32, 3, activation = 'relu')(x)
x = tf.keras.layers.MaxPooling2D(3)(x)
x = tf.keras.layers.Conv2D(32, 3,activation = 'relu')(x)
x = tf.keras.layers.Conv2D(16, 3, activation = 'relu')(x)
encoder_output = tf.keras.layers.GlobalMaxPooling2D()(x)

encoder = tf.keras.Model(inputs=encoder_input, outputs=encoder_output, name = 'encoder')
encoder.summary()

#Decoder
decoder_input = tf.keras.layers.Reshape((4, 4, 1))(encoder_output)
x = tf.keras.layers.Conv2DTranspose(16, 3, activation = 'relu')(decoder_input)
x = tf.keras.layers.Conv2DTranspose(32, 3, activation = 'relu')(x)
x = tf.keras.layers.UpSampling2D(3)(x)
x = tf.keras.layers.Conv2DTranspose(16, 3, activation = 'relu')(x)
decoder_output = tf.keras.layers.Conv2DTranspose(1, 3, activation = 'relu')(x)


autoencoder = keras.Model(inputs = encoder_input, outputs = decoder_output, name='autoencoder')
autoencoder.summary()

输出:

x_train shape: (60000, 32, 32, 3)
60000 train samples
10000 test samples
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input (InputLayer)           (None, 32, 32, 3)         0         
_________________________________________________________________
conv2d_35 (Conv2D)           (None, 30, 30, 16)        448       
_________________________________________________________________
conv2d_36 (Conv2D)           (None, 28, 28, 32)        4640      
_________________________________________________________________
max_pooling2d_8 (MaxPooling2 (None, 9, 9, 32)          0         
_________________________________________________________________
conv2d_37 (Conv2D)           (None, 7, 7, 32)          9248      
_________________________________________________________________
conv2d_38 (Conv2D)           (None, 5, 5, 16)          4624      
_________________________________________________________________
global_max_pooling2d_8 (Glob (None, 16)                0         
=================================================================
Total params: 18,960
Trainable params: 18,960
Non-trainable params: 0
_________________________________________________________________
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input (InputLayer)           (None, 32, 32, 3)         0         
_________________________________________________________________
conv2d_35 (Conv2D)           (None, 30, 30, 16)        448       
_________________________________________________________________
conv2d_36 (Conv2D)           (None, 28, 28, 32)        4640      
_________________________________________________________________
max_pooling2d_8 (MaxPooling2 (None, 9, 9, 32)          0         
_________________________________________________________________
conv2d_37 (Conv2D)           (None, 7, 7, 32)          9248      
_________________________________________________________________
conv2d_38 (Conv2D)           (None, 5, 5, 16)          4624      
_________________________________________________________________
global_max_pooling2d_8 (Glob (None, 16)                0         
_________________________________________________________________
reshape_6 (Reshape)          (None, 4, 4, 1)           0         
_________________________________________________________________
conv2d_transpose_16 (Conv2DT (None, 6, 6, 16)          160       
_________________________________________________________________
conv2d_transpose_17 (Conv2DT (None, 8, 8, 32)          4640      
_________________________________________________________________
up_sampling2d_4 (UpSampling2 (None, 24, 24, 32)        0         
_________________________________________________________________
conv2d_transpose_18 (Conv2DT (None, 26, 26, 16)        4624      
_________________________________________________________________
conv2d_transpose_19 (Conv2DT (None, 28, 28, 1)         145       
=================================================================
Total params: 28,529
Trainable params: 28,529
Non-trainable params: 0
_________________________________________________________________