ValueError: Shape must be rank 1 but is rank 0 for ‘batch_normalization_1/cond/Reshape_4‘ (op: ‘Resh

ValueError: Shape must be rank 1 but is rank 0 for ‘batch_normalization_1/cond/Reshape_4’ (op: ‘Reshape’) with input shapes: [1,64,1,1], [].

在跑crnn和rcnn相关代码时,有遇到上述错误,错误信息如下:
在这里插入图片描述

实例代码如下:

# os.environ['CUDA_VISIBLE_DEVICES']='-1'
import keras.backend as K
from keras.layers import Activation, Conv2D, Input,Dense
from keras.layers.normalization import BatchNormalization
from keras.models import Model
# from tensorflow.examples.tutorials.mnist import input_data
import keras
from keras.datasets import mnist
from sklearn.preprocessing import OneHotEncoder
import numpy as np
#
#准备数据
# mnist = input_data.read_data_sets('D:/DataSet/mnist',one_hot=True)
(trainX, trainY), (testX, testY) = mnist.load_data('D:/DataSet/mnist/mnist.npz')
trainY_onehot = np.zeros(shape=(trainY.shape[0],10))
testY_onehot = np.zeros(shape=(testY.shape[0],10))
#用现有方法onehot
trainY_onehot = keras.utils.to_categorical(trainY,10)
#相当于trainY_onehot[np.arange(y.shape[0]),y]=1
testY_onehot = keras.utils.to_categorical(testY,10)
print(trainX.shape,trainY_onehot.shape,testX.shape,testY_onehot.shape)


#数据预处理,这channels和对应image和input要一致;input不包含batch
K.set_image_data_format('channels_first')
train_image = trainX.reshape(-1,1,28,28)
test_image = testX.reshape(-1,1,28,28)
input = Input(shape=(1,28,28), dtype='float32')

#搭建网络
x = Conv2D(filters=64, kernel_size=(3, 3), strides=1, padding='same')(input)
#BN没有axis参数可以;查看文档说要是接在channel_first的2二维卷积后,那么要设置为1
x = BatchNormalization(axis=1)(x)
x = Activation('relu')(x)
#卷积和全连接要flatten,keras也要
x = keras.layers.Flatten()(x)
x = Dense(128,activation='relu')(x)
y = Dense(10,activation='softmax')(x)

#训练网络
model = Model(input=input,outputs=y)
model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.SGD(),metrics=['accuracy'])
model.fit(train_image,trainY_onehot,validation_data=(test_image,testY_onehot),epochs=5,batch_size=128)

错误发生在33行处,查阅相关资料,发现是在keras设置channel_first格式的输入数据时,使用了BN的axis参数,将其设置为1导致的。
查阅了很多博客都说是将keras的版本替换为旧的或新的版本,考虑遇到问题不能就随便更换版本了事,于是去查资料,发现原github上有一个解决方法:
解决方法图
意思是将错误信息示例图片中tensorflow_backend.py的1908,1910,1914和1918行的reshape里的小括号()替换为中括号[]。经测试改完后代码没有问题了。

为什么呢?

肯定是tf.reshape的原因了。这里应该是想要通过reshape,将均值mean展开成一维数组,类似于numpy中的np.reshape(-1,)。去看tf.reshape的源码文档,这里传入[-1]就是将输入展开成1维,验证了猜想,当然这里也可以改为(-1,)来将输入展开成一维,虽然这样做原tf.reshape的文档没有给出实例。

示例代码:

import tensorflow as tf
a = tf.constant([[1,2],[3,4]])
b = tf.reshape(a,(-1))#换成(-1)不可用,要是换成(-1,)也可用,,,
with tf.Session() as sess:
    print(a,a.shape)
    print(b.eval(),b)

tf.reshape源码文档:

没有啦,自己找
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值