CNN卷积层到全连接层的输入格式变换错误 tf.reshape()和slim.flatten()

TypeError: Failed to convert object of type < type ‘list’>to Tensor. Contents: [None, 9216]. Consider casting elements to a supported type.


在CNN卷积神经网络中,卷积层和全连接层进行连接时有个输入格式转换过程,即卷积层的输出是一个x*y*z的矩阵,而全连接层的输入是一个向量,需要把矩阵拉直成向量。我的程序中使用了如下代码:

# 卷积层9
weights9 = tf.get_variable('weights9', shape=[3, 3, 256, 256], dtype=tf.float32,
                          initializer=tf.contrib.layers.xavier_initializer(False))
conv9 = tf.nn.conv2d(actived_conv8, weights9, strides=[1, 1, 1, 1], padding='SAME')
conv9 = tf.contrib.layers.batch_norm(conv9, is_training=is_train)
actived_conv9 = tf.nn.relu(conv9)
# 全连接层,将矩阵拉直成一个向量
conv_shape = actived_conv9.get_shape().as_list()
nodes = conv_shape[1]*conv_shape[2]*conv_shape[3]            # 向量的长度为矩阵的长宽及深度的乘积
reshaped = tf.reshape(actived_conv9,[conv_shape[0],nodes])   # conv_shape[0]为一个batch中数据的个数
# 全连接层1
fc1_weights = tf.get_variable('fc_weights', shape=[nodes, 512],dtype = tf.float32,
                              initializer=tf.contrib.layers.xavier_initializer(False))
if regularizer != None:     # 正则化,只在全连接层的权重使用
    tf.add_to_collection('losses',regularizer(fc1_weights))
fc1_biases = tf.get_variable('fc1_biases',[512],initializer=tf.constant_initializer(0.1))
fc1 = tf.nn.relu(tf.matmul(reshaped,fc1_weights) + fc1_biases)

然而程序运行中报出了如下的错误:TypeError: Failed to convert object of type < type ‘list’> to Tensor. Contents: [None, 9216]. Consider casting elements to a supported type.

在检查程序后发现问题出在conv_shape[0]上面,在卷积输入占位符里使用的是如下代码:

x_Label = tf.placeholder(tf.float32,[None,patch_size,patch_size,band])

注意shape第一维使用的是None,这是便于输入的batch大小的调整,然而在conv_shape= actived_conv9.get_shape().as_list()中shape读取时conv_shape[0]读取到的是None, tf.reshape(actived_conv9,[conv_shape[0],nodes]) 函数无法将卷积层输出的矩阵转换为向量。

最开始我的解决办法是将conv_shape[0] 直接换成batch的大小,这样解决了此问题,但在后面的调试过程中又出现另外的bug,所以不是好的方案。

最后采用的是使用slim.flatten()函数,直接进行转换,不需要读取shape的大小,代码如下:

conv9 = tf.contrib.layers.batch_norm(conv9, is_training=is_train)
actived_conv9 = tf.nn.relu(conv9)

#全连接层,将矩阵拉直成一个向量
reshaped = slim.flatten(actived_conv9)      
conv_shape = actived_conv9.get_shape().as_list()
nodes = conv_shape[1]*conv_shape[2]*conv_shape[3]   # 向量的长度为矩阵的长宽及深度的乘积

#全连接层1
fc1_weights = tf.get_variable('fc_weights', shape=[nodes, 512],dtype = tf.float32,
                              initializer=tf.contrib.layers.xavier_initializer(False))
if regularizer != None:     # 正则化,只在全连接层的权重使用
   tf.add_to_collection('losses',regularizer(fc1_weights))
fc1_biases = tf.get_variable('fc1_biases',[512],initializer=tf.constant_initializer(0.1))
fc1 = tf.nn.relu(tf.matmul(reshaped,fc1_weights) + fc1_biases)

猜你喜欢

转载自blog.csdn.net/kewendouhe/article/details/81530841