通过将PCA添加到算法中,我正在努力提高%96.5的kalegle数字识别教程的SKlearn kNN预测分数,但是基于PCA输出的新kNN预测却像23%一样可怕。

以下是完整的代码,如果您指出我错了的地方,我将不胜感激。

import pandas as pd
import numpy as np
import pylab as pl
import os as os
from sklearn import metrics
%pylab inline
os.chdir("/users/******/desktop/python")

traindata=pd.read_csv("train.csv")
traindata=np.array(traindata)
traindata=traindata.astype(float)
X,y=traindata[:,1:],traindata[:,0]

from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test= train_test_split(X,y,test_size=0.25, random_state=33)

#scale & PCA train data
from sklearn import preprocessing
from sklearn.decomposition import PCA
X_train_scaled = preprocessing.scale(X_train)
estimator = PCA(n_components=350)
X_train_pca = estimator.fit_transform(X_train_scaled)

# sum(estimator.explained_variance_ratio_) = 0.96

from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=6)
neigh.fit(X_train_pca,y_train)

# scale & PCA test data
X_test_scaled=preprocessing.scale(X_test)
X_test_pca=estimator.fit_transform(X_test_scaled)

y_test_pred=neigh.predict(X_test_pca)
# print metrics.accuracy_score(y_test, y_test_pred) = 0.23
# print metrics.classification_report(y_test, y_test_pred)

最佳答案

在处理测试数据时,您使用了fit_transform(X_test),它实际上重新计算了测试数据上的另一个PCA转换。您应该使用transform(X_test),以便测试数据与训练数据进行相同的转换。

代码的一部分看起来像(感谢ogrisel的whiten技巧):

estimator = PCA(n_components=350, whiten=True)
X_train_pca = estimator.fit_transform(X_train)
X_test_pca = estimator.transform(X_test)

尝试看看是否有帮助?

关于python - SKLearn-主成分分析导致knn预测中的可怕结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21331160/

10-10 04:59