卷积神经网络上的PCA实现

时间:2019-01-05 02:08:55

标签: python pandas conv-neural-network pca

在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

1 个答案:

答案 0 :(得分:1)

我解决了这个问题,更新了帖子,让其他程序员可以直观地调试他们的代码。首先,我在X_test数据上应用了PCA,并且在得分较低后尝试不使用。正如@Scott所建议的,这是错误的。仔细检查代码后,我发现在构建CNN模型时将PCA应用于测试数据后,我忘记将X_test更改为X_test_pca。在将PCA应用于X_test数据时,我还在X_train上安装了PCA。