当前位置: 首页 > 知识库问答 >
问题:

预期ndim=4发现ndim=5和其他错误-Keras-GTSRB数据集

秦信瑞
2023-03-14

我试图基于GTSRB数据集(下面给出的链接)制作一个CNN模型,但我面临以下错误:

当我设置input\u shape=input\u shape=(3,IMG\u SIZE,IMG\u SIZE)时,我得到以下错误:

ValueError:检查输入时出错:预期conv2d\u 34\u输入有4个维度,但得到了具有形状的数组(9030,1)

当我研究这个问题时,我发现一个解决方案可能是将batch_size作为参数传递,当我尝试时,我得到了这个错误:

ValueError:输入0与层conv2d\U 40不兼容:预期ndim=4,发现ndim=5

当我试图重塑training_images时,我得到了这个错误:

ValueError:无法将大小为9030的数组重塑为形状(48,48,3)

代码片段:加载培训数据集:

import csv

# Training dataset
def readTrafficSignsTrain(rootpath):
    '''Reads traffic sign data for German Traffic Sign Recognition Benchmark.

    Arguments: path to the traffic sign data, for example './GTSRB/Training'
    Returns:   list of images, list of corresponding labels'''
    images = [] # images
    labels = [] # corresponding labels

    # loop over all 42 classes
    for c in range(0,43):
#         prefix = rootpath + '/' + format(c, '05d') + '/' # subdirectory for class
#         annFile = open(prefix + 'GT-'+ format(c, '05d') + '.csv') # annotations file
        prefix = rootpath + '/00000' + '/'
        annFile = open(prefix + 'GT-00000' + '.csv')
        annReader = csv.reader(annFile, delimiter=';') # csv parser for annotations file
        next(annReader, None) # skip header

        # loop over all images in current annotations file
        for row in annReader:
            images.append(plt.imread(prefix + row[0])) # the 1st column is the filename
            labels.append(row[7]) # the 8th column is the label

        annFile.close()
    return images, labels

training_images, training_labels = readTrafficSignsTrain('./GTSRB/Training')

这里有一个问题,图像形状不一样,例如

print(len(training_images))
print(len(training_labels))
print()
print(training_images[0].shape)
print(training_images[20].shape)
print(training_images[200].shape)
print(training_images[2000].shape)

输出

9030 9030

(30, 29, 3) (54, 57, 3) (69, 63, 3) (52, 51, 3)

层设置(从下面链接的Keras留档复制粘贴):

IMG_SIZE = 48
NUM_CLASSES = 43
K.set_image_data_format('channels_first')

batch_size = 32

def cnn_model():
    model = Sequential()

    model.add(Conv2D(32, (3, 3), padding='same',
                     input_shape=(3, IMG_SIZE, IMG_SIZE),
                     activation='relu',
                     data_format="channels_first"))
    model.add(Conv2D(32, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_first"))
    model.add(Dropout(0.2))

    model.add(Conv2D(64, (3, 3), padding='same',
                     activation='relu'))
    model.add(Conv2D(64, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))

    model.add(Conv2D(128, (3, 3), padding='same',
                     activation='relu'))
    model.add(Conv2D(128, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))

    model.add(Flatten())
    model.add(Dense(512, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(NUM_CLASSES, activation='softmax'))
    return model

model = cnn_model()

培训模型(仅model.fit暂时适用

import numpy

trim = numpy.array(training_images)
trlb = numpy.array(training_labels)

print(training_images[0].shape)
print(trim.shape)

trim - trim.reshape(48, 48, 3)

model.fit(trim, trlb, epochs = 30, batch_size = 32)

输出

ValueError:无法将大小为9030的数组重塑为形状(48,48,3)

当我移除重塑时

ValueError:检查输入时出错:预期conv2d\u 41\u输入有4个维度,但得到了具有形状的数组(9030,1)

当我改用这个的时候

model.fit(training_images, training_labels, epochs = 30, batch_size = 32)

输出

> ValueError: Error when checking model input: the list of Numpy arrays
> that you are passing to your model is not the size the model expected.
> Expected to see 1 array(s), but instead html" target="_blank">got the following list of 9030
> arrays: [array([[[ 75,  78,  80],
>             [ 74,  76,  78],
>             [ 86,  87,  84],
>             ...,
>             [ 68,  75,  75],
>             [ 65,  69,  68],
>             [ 66,  67,  66]],
>     
>            [[ 83,  84,  86],
>             [...

所以,如果我这样做(不知道为什么)

for i in range(len(training_images)):
    model.fit(training_images[i], training_labels[i], epochs = 30, batch_size = 32)

我得到

ValueError:检查输入时出错:预期conv2d_41_input有4个维度,但得到了带有形状(30,29,3)的数组

这就是

input_shape=(3, IMG_SIZE, IMG_SIZE)

如果我让

input_shape=(batch_size, 3, IMG_SIZE, IMG_SIZE)

我明白了

ValueError:输入0与层conv2d\U 47不兼容:预期ndim=4,发现ndim=5

模型的输出。摘要()

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_34 (Conv2D)           (None, 32, 48, 48)        896       
_________________________________________________________________
conv2d_35 (Conv2D)           (None, 32, 46, 46)        9248      
_________________________________________________________________
max_pooling2d_14 (MaxPooling (None, 32, 23, 23)        0         
_________________________________________________________________
dropout_14 (Dropout)         (None, 32, 23, 23)        0         
_________________________________________________________________
conv2d_36 (Conv2D)           (None, 64, 23, 23)        18496     
_________________________________________________________________
conv2d_37 (Conv2D)           (None, 64, 21, 21)        36928     
_________________________________________________________________
max_pooling2d_15 (MaxPooling (None, 64, 10, 10)        0         
_________________________________________________________________
dropout_15 (Dropout)         (None, 64, 10, 10)        0         
_________________________________________________________________
conv2d_38 (Conv2D)           (None, 128, 10, 10)       73856     
_________________________________________________________________
conv2d_39 (Conv2D)           (None, 128, 8, 8)         147584    
_________________________________________________________________
max_pooling2d_16 (MaxPooling (None, 128, 4, 4)         0         
_________________________________________________________________
dropout_16 (Dropout)         (None, 128, 4, 4)         0         
_________________________________________________________________
flatten_4 (Flatten)          (None, 2048)              0         
_________________________________________________________________
dense_10 (Dense)             (None, 512)               1049088   
_________________________________________________________________
dropout_17 (Dropout)         (None, 512)               0         
_________________________________________________________________
dense_11 (Dense)             (None, 43)                22059     
=================================================================
Total params: 1,358,155
Trainable params: 1,358,155
Non-trainable params: 0
_________________________________________________________________
None

如果有人能帮忙,那将不胜感激。

链接GTSRB:http://benchmark.ini.rub.de/?section=gtsrb

github上完整项目的链接:https://github.com/PavlySz/TSR-Project

谢谢

共有1个答案

陈茂
2023-03-14

你不能把np.array改造成一个不允许的东西

import numpy as np 
img_arr = np.array([np.ones((30, 29, 3)), 
                    np.ones((54, 57, 3)), 
                    np.ones((69, 63, 3)), 
                    np.ones((52, 51, 3))])

print(img_arr.shape)

import cv2
img_arr_conv = np.array([cv2.resize(img, dsize=(48, 48)) for img in img_arr])
print(img_arr_conv.shape)

>>>(4,)
>>>(4, 48, 48, 3)

您得到的是值错误:无法将大小为9030的数组重塑为形状(48,48,3),因为如果元素的大小都不同,numpy无法推断数组的尺寸,并且无法重塑尺寸不允许的数组。值错误的情况也是如此:检查输入时出错:预期conv2d\u 41\u输入有4个维度,但得到的数组具有形状(9030,1)。Numpy只知道数组中有9030个元素。它不能做更多的事情,因为元素的所有维度都是不同的
示例

img_arr_bad = np.array([np.ones((30, 29, 3)), 
                        np.ones((54, 57, 3)), 
                        np.ones((69, 63, 3)), 
                        np.ones((52, 51, 3))])

img_arr_good = np.array([np.ones((48, 48, 3)), 
                         np.ones((48, 48, 3)), 
                         np.ones((48, 48, 3)), 
                         np.ones((48, 48, 3))])

print(img_arr_bad.shape)
print(img_arr_good.shape)

>>>(4,)
>>>(4, 48, 48, 3)

希望这有帮助

 类似资料:
  • 问题内容: 我已经检查了所有解决方案,但仍然遇到相同的错误。我的训练图像形状是,我相信它是4维的,但是我不知道为什么错误显示它是5维的。 所以这就是我的定义 问题答案: 问题是。 它实际上应该仅包含3个维度。内部keras将添加批次尺寸使其成为4。 由于您可能使用了4维(包括批处理),因此keras将添加5维。 您应该使用。

  • 我正在使用下面的代码使用GRU预测下一个单词。 低于异常。请帮我解决这个问题?? AttributeError Traceback(最近一次调用),在- c:\ users \ dixit \ appdata \ local \ programs \ python \ python 38 \ lib \ site-packages \ keras \ engine \ training . py

  • 我在Jupyter Notebook中运行Keras神经网络模型(Python 3.6) 我得到以下错误 属性错误:列表对象没有属性ndim 从K调用. fi()方法后eras.model 我检查了Keras的requirements.txt文件(在Anaconda3中),Numpy、smpy和六个模块版本都是最新的。 什么可以解释这个属性错误? 完整的错误消息如下(似乎与Numpy有些关联):

  • 我正在尝试微调VGG16神经网络,下面是代码: 我得到这个错误: ValueError Traceback(最近一次调用上次)位于 2型号。添加(vgg16\U型号) 3#添加完全连接的层: ---- 5型号。添加(密集(256,激活='relu')) 6型号。添加(辍学(0.5)) /usr/local/anaconda/lib/python3.6/site-packages/keras/eng

  • 我试图从教程中在<code>python。我的代码可能有什么错误,如下所示?我感谢你的支持。 法典:

  • 我不断地得到这个错误,我并没有试图解决它。 包bonuscalc; 导入java.text.DecimalFormat;导入java.util.scanner; 公共类BonusCalc{/***@param args命令行参数*/public static void main(String[]args){ }