ValueError: 滤波器的尺寸不能大于输入尺寸

我对机器学习还比较陌生,所以我在尝试一些示例代码。代码中指定的图像尺寸是(28,28),但不知为何我总是得到相同的ValueError错误,我搞不清楚为什么会这样。

这是我的代码:

import pandas as pdimport numpy as npnp.random.seed(1337) # for reproducibilityfrom keras.models import Sequentialfrom keras.layers.core import Dense, Dropout, Activation, Flattenfrom keras.layers.convolutional import Convolution2D, MaxPooling2Dfrom keras.utils import np_utils# input image dimensionsimg_rows, img_cols = 28, 28batch_size = 128 # Number of images used in each optimization stepnb_classes = 10 # One class per digitnb_epoch = 35 # Number of times the whole data is used to learn# Read the train and test datasetstrain = pd.read_csv("../input/train.csv").valuestest  = pd.read_csv("../input/test.csv").values# Reshape the data to be used by a Theano CNN. Shape is# (nb_of_samples, nb_of_color_channels, img_width, img_heigh)X_train = train[:, 1:].reshape(train.shape[0], 1, img_rows, img_cols)X_test = test.reshape(test.shape[0], 1, img_rows, img_cols)y_train = train[:, 0] # First data is label (already removed from X_train)# Make the value floats in [0;1] instead of int in [0;255]X_train = X_train.astype('float32')X_test = X_test.astype('float32')X_train /= 255X_test /= 255# convert class vectors to binary class matrices (ie one-hot vectors)Y_train = np_utils.to_categorical(y_train, nb_classes)#Display the shapes to check if everything's okprint('X_train shape:', X_train.shape)print('Y_train shape:', Y_train.shape)print('X_test shape:', X_test.shape)model = Sequential()# For an explanation on conv layers see http://cs231n.github.io/convolutional-networks/#conv# By default the stride/subsample is 1# border_mode "valid" means no zero-padding.# If you want zero-padding add a ZeroPadding layer or, if stride is 1 use border_mode="same"model.add(Convolution2D(12, 5, 5, border_mode='valid',input_shape=(1,img_rows, img_cols)))model.add(Activation('relu'))# For an explanation on pooling layers see http://cs231n.github.io/convolutional-networks/#poolmodel.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.15))model.add(Convolution2D(24, 5, 5))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.15))# Flatten the 3D output to 1D tensor for a fully connected layer to accept the inputmodel.add(Flatten())model.add(Dense(180))model.add(Activation('relu'))model.add(Dropout(0.5))model.add(Dense(100))model.add(Activation('relu'))model.add(Dropout(0.5))model.add(Dense(nb_classes)) #Last layer with one output per classmodel.add(Activation('softmax')) #We want a score simlar to a probability for each class# The function to optimize is the cross entropy between the true label and the output (softmax) of the model# We will use adadelta to do the gradient descent see http://cs231n.github.io/neural-networks-3/#adamodel.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=["accuracy"])# Make the model learnmodel.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1)# Predict the label for X_testyPred = model.predict_classes(X_test)# Save prediction in file for Kaggle submissionnp.savetxt('mnist-pred.csv', np.c_[range(1,len(yPred)+1),yPred], delimiter=',', header = 'ImageId,Label', comments = '', fmt='%d')

回答:

所以问题出在所使用的卷积尺寸上。卷积操作通常会减小图像的尺寸。同样,每次池化操作也会减小尺寸。你使用的是非常小的图像,但却应用了为更大图像设计的模型架构,因此在某个点上,经过一次卷积/池化后,输出的图像尺寸实际上比后续的滤波器尺寸还要小,这是一个未定义的操作。

要暂时解决这个问题,可以移除第二个卷积和最大池化层,因为这些操作(使用提供的参数)无法在如此小的数据上进行。总的来说,你应该首先理解卷积是如何工作的,而不是直接应用别人的模型,因为参数对性能至关重要——如果你应用的变换过度降低了分辨率,你将无法学到任何东西。因此,一旦你对卷积的工作原理有了直觉,你可以返回并尝试不同的架构,但没有一个“神奇”的公式可以确定架构,因此我无法提供“直接有效”的参数——先从移除这个额外的卷积和池化开始,然后在你对数据和模型有了更好的理解后,再尝试其他可能性。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注