Keras CNN与SVM结合时目标值重塑问题修复求助
解决SVM与CNN结合时的目标值重塑问题
问题根源
你遇到的ValueError是因为**y_train已经被转换成了独热编码格式**(形状(2480,2)),当你取前50个样本时,得到的是(50,2)的二维数组,总元素数是100,自然无法重塑成(50,)的一维数组。而SVM需要的是一维的类别标签(0/1),不是独热编码的二维矩阵。
解决方案步骤
还原独热编码为原始类别标签
在你准备将标签传入SVM之前,先用np.argmax()把独热编码转换成一维的类别索引:# 把独热编码的y_train、y_test还原成原始标签(0或1) y_train_labels = np.argmax(y_train, axis=1) y_test_labels = np.argmax(y_test, axis=1)这时候
y_train_labels的形状会变成(2480,),正好是SVM需要的格式。提取对应样本的标签
现在再取前50个训练标签和前10个测试标签,不需要额外reshape:y_train_svm = y_train_labels[:50] y_test_svm = y_test_labels[:10]修正SVM的评估代码
你后面用model.evaluate(exTrain, y_train)是错误的,因为model是CNN模型,它的输入要求是原始图像格式((n,1,513,125)),而exTrain是CNN提取的特征(来自model.layers[7].output)。应该用SVM自身的score方法来评估:from sklearn.svm import SVC clf = SVC(gamma='auto') clf.fit(exTrain, y_train_svm) # 评估SVM的训练集准确率 score_train_svm = clf.score(exTrain, y_train_svm) print('SVM Train accuracy:', score_train_svm) # 评估SVM的测试集准确率 score_test_svm = clf.score(exTest, y_test_svm) print('SVM Test accuracy:', score_test_svm)
完整修改后的关键代码片段
把你主函数里的相关代码替换成下面这段:
# feature extraction layer getFeature = K.function([model.layers[0].input, K.learning_phase()], [model.layers[7].output]) # classification layer getPrediction = K.function([model.layers[8].input, K.learning_phase()], [model.layers[9].output]) exTrain = getFeature([X_train[:50], 0])[0] exTest = getFeature([X_test[:10], 0])[0] # 还原独热编码为原始标签 y_train_labels = np.argmax(y_train, axis=1) y_test_labels = np.argmax(y_test, axis=1) y_train_svm = y_train_labels[:50] y_test_svm = y_test_labels[:10] print(exTrain.shape, exTest.shape, y_train_svm.shape, y_test_svm.shape) from sklearn.svm import SVC clf = SVC(gamma='auto') clf.fit(exTrain, y_train_svm) # 用SVM的score方法评估 score_train_svm = clf.score(exTrain, y_train_svm) print('SVM Train accuracy:', score_train_svm) score_test_svm = clf.score(exTest, y_test_svm) print('SVM Test accuracy:', score_test_svm)
这样就能解决你遇到的重塑错误,同时正确用SVM对CNN提取的特征进行分类和评估了。
内容的提问来源于stack exchange,提问作者root
相关产品推荐
相关产品推荐

