通过将 PCA 添加到算法中,我正在努力提高 kaggle 数字识别教程的 %96.5 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)