ValueError:输入 0 与层 conv2d_1 不兼容:预期 ndim=4,发现 ndim=3 [英] ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=3

查看:43
本文介绍了ValueError:输入 0 与层 conv2d_1 不兼容:预期 ndim=4,发现 ndim=3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在询问了已经提出的关于这个问题的问题之后,我继续提出它.我试图将字母从 A 分类到 D.所有输入图像都是 64x64 和灰色.

After inquiring into the questions already asked about this problem, I keep presenting it. Im trying to classify letters from A to D. All input images are 64x64 and graycolor.

我的 CNN 的第一层是:

The first layer of my CNN is:

model = Sequential()
model.add(Conv2D(32, (3,  3), input_shape = input_shape, activation = 'relu'))

input_shape 它来自:

# Define the number of classes
num_classes = 4
labels_name={'A':0,'B':1,'C':2,'D':3}

img_data_list=[]
labels_list=[]

for dataset in data_dir_list:
    img_list=os.listdir(data_path+'/'+ dataset)
    print ('Loading the images of dataset-'+'{}\n'.format(dataset))
    label = labels_name[dataset]
    for img in img_list:
    input_img=cv2.imread(data_path + '/'+ dataset + '/'+ img )
          input_img=cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY)
          input_img_resize=cv2.resize(input_img,(128,128))
          img_data_list.append(input_img_resize)
          labels_list.append(label)

img_data = np.array(img_data_list)
img_data = img_data.astype('float32')
img_data /= 255
print (img_data.shape)

labels = np.array(labels_list)
print(np.unique(labels,return_counts=True))

#convert class labels to on-hot encoding
Y = np_utils.to_categorical(labels, num_classes)

#Shuffle the dataset
x,y = shuffle(img_data,Y, random_state=2)

# Split the dataset
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2)

#Defining the model
input_shape=img_data[0].shape
print(input_shape)

推荐答案

Conv2d 需要输入形状(batchsize、w、h、filters).

Conv2d expects input of shape (batchsize, w, h, filters).

你需要在conv层之前添加一个reshape来适应数据:

You need to add a reshape to fit the data before the conv layer:

 model.add(Reshape((64, 64, 1)))

这会将您的模型尺寸设置为 [None, 64,64,1],对于 Conv2d 应该没问题.

This will set your model dimensions to [None, 64,64,1] and should be fine for Conv2d.

这篇关于ValueError:输入 0 与层 conv2d_1 不兼容:预期 ndim=4,发现 ndim=3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆