预期的conv2d输入具有形状5665,445,3,但是形状不佳1,445,3

问题描述

我有输入形状的数据(5665,445,3),但是在运行代码时出现此错误expected conv2d input to have shape (5665,3) but got aaray with shape (1,3),这不是为什么。任何我知道为什么会收到此错误以及如何解决它??

代码

def generate_arrays_for_training(indexPat,paths,start=0,end=100):     
    while True:
        from_=int(len(paths)/100*start)
        to_=int(len(paths)/100*end)
        for i in range(from_,int(to_)):
            f=paths[i]
            x = np.load(PathSpectogramFolder+f)
            x=x[:,:,:-1] #3channels
            x=np.array([x])
            x=x.swapaxes(0,1)
            if('P' in f):
                y = np.repeat([[0,1]],x.shape[0],axis=0)
            else:
                y =np.repeat([[1,0]],axis=0)
            yield(x,y)
def createModel():
    input_shape=(5665,3)
    model = Sequential()
    model.add(Conv2D(16,( 5,5),strides=( 2,2),padding='same',activation='relu',data_format= "channels_last",input_shape=input_shape))
    model.add(keras.layers.MaxPooling2D(pool_size=( 2,padding='same'))
    model.add(Batchnormalization())
    model.add(Conv2D(32,( 3,3),strides=( 1,1),activation='relu'))
    model.add(keras.layers.MaxPooling2D(pool_size=(2,padding='same' ))
    model.add(Batchnormalization())
    model.add(Conv2D(64,(3,strides=(1,padding='same' ))
    model.add(Batchnormalization())
    model.add(Flatten())
    model.add(Dropout(0.5))
    model.add(Dense(256,activation='sigmoid'))
    model.add(Dropout(0.5))
    model.add(Dense(2,activation='softmax'))
return model

解决方法

为什么形状为(1,445,3)的错误数组

检查完代码后,我发现您的函数generate_arrays_for_training将返回x.shape is (5665,1,3)的形状。看来它发生在x=x.swapaxes(0,1)行,它交换了第一维和第二维的空间。

注释该行将返回更好的x.shape is (1,5665,3)

工作代码

我已经重写并简化了您的生成器,并提供了对其进行测试的支持代码

import numpy as np

def make_training():
    for i in range(10):
        name = f'data/item{i}'
        np.save(name,np.zeros([5665,4]))
        yield name+'.npy'

paths = [ _ for _ in make_training() ]
PathSpectogramFolder ='./'

def generate_arrays_for_training(paths):     
    while True:
        for path in paths:
            x = np.load(PathSpectogramFolder+path)
            x=x[:,:,:-1] #3channels
            x=np.array([x])
            if('P' in path):
                y = np.repeat([[0,1]],x.shape[0],axis=0)
            else:
                y = np.repeat([[1,0]],axis=0)
            yield(x,y)

gen = generate_arrays_for_training(paths)
x,y = next(gen)
print('x.shape is',x.shape)
print('y.shape is',y.shape)

输出是这样的:

x.shape is (1,3)
y.shape is (1,2)