在对MNIST数据应用PCA后,我确定了CNN模型和层。在拟合CNN模型(X_train_PCA,Y_train)后,我最终在评估阶段遇到了维度问题。这是消息"ValueError:检查输入时出错:预期conv2d_1_input具有形状(1,10,10),但得到形状为(1,28,28)的数组"。当我尝试将X_test重塑为 10X10 格式时,我得到了非常低的分数
首先,我应用最小-最大正则化,然后应用PCA来X_train。然后,我从X_train生成了验证数据。问题是;我可以以 100 维格式拟合数据(应用 PCA 后),我的输入数据变为 10X10。当我尝试使用仍然为 (10000, 1, 28, 28) 的 X_test 从拟合模型中获取分数时。我收到如上所述的错误。如何解决尺寸问题。我还尝试使用 minmaxscaler 和 PCA 转换X_test。分数没有变化
pca_3D = PCA(n_components=100)
X_train_pca = pca_3D.fit_transform(X_train)
X_train_pca.shape
cnn_model_1_scores = cnn_model_1.evaluate(X_test, Y_test, verbose=0)
# Split the data into training, validation and test sets
X_train1 = X_pca_proj_3D[:train_size]
X_valid = X_pca_proj_3D[train_size:]
Y_train1 = Y_train[:train_size]
Y_valid = Y_train[train_size:]
# We need to convert the input into (samples, channels, rows, cols) format
X_train1 = X_train1.reshape(X_train1.shape[0], 1, 10,
10).astype('float32')
X_valid = X_valid.reshape(X_valid.shape[0], 1, 10, 10).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')
X_train1.shape, X_valid.shape, X_test.shape
((51000, 1, 10, 10), (9000, 1, 10, 10), (10000, 1, 28, 28))
#create model
cnn_model_1=Sequential()
#1st Dense Layer
cnn_model_1.add(Conv2D(32, kernel_size=(5,5),
data_format="channels_first",
input_shape=(1,10,10),
activation='relu'))
#Max-Pooling
cnn_model_1.add(MaxPooling2D(pool_size=(2,2)))
#Max pooling is a sample-based discretization process. The objective is to
down-sample an input representation (image, hidden-layer output matrix,
etc.), reducing its dimensionality
# the number of layers, remains unchanged in the pooling operation
#cnn_model_1.add(BatchNormalization())
#Dropout
cnn_model_1.add(Flatten())
#cnn_model_1.add(BatchNormalization())
#2nd Dense Layer
cnn_model_1.add(Dense(128, activation='relu'))
#final softmax layer
cnn_model_1.add(Dense(10, activation='softmax'))
# print a summary and check if you created the network you intended
cnn_model_1.summary()
#Compile Model
cnn_model_1.compile(loss='categorical_crossentropy', optimizer='adam',
metrics=['accuracy'])
#Fit the model
cnn_model_1_history=cnn_model_1.fit(X_train1, Y_train1,
validation_data=(X_valid, Y_valid), epochs=5, batch_size=100, verbose=2)
# Final evaluation of the model
cnn_model_1_scores = cnn_model_1.evaluate(X_test, Y_test, verbose=0)
print("Baseline Test Accuracy={0:.2f}% (categorical_crossentropy) loss=
{1:.2f}".format(cnn_model_1_scores[1]*100, cnn_model_1_scores[0]))
cnn_model_1_scores
我解决了这个问题,更新了帖子,为其他编码人员提供了调试代码的直觉。首先,我对X_test数据应用了PCA,在得到低分后,我尝试了没有申请。正如@Scott所暗示的那样,这是错误的。仔细检查我的代码后,我发现在构建 CNN 模型时对测试数据应用 PCA 后,我忘记将X_test更改为 X_test_pca。我还在X_train上安装了 PCA,同时对X_test数据应用 PCA。