def predictKFoldKNN(X, y, K=10, kfold=10, selectKBest=0):
"""
Classifies the data using K-nearest neighbors and k-fold CV
:param X: The list of feature vectors
:type X: list
:param y: The list of labels corresponding to the feature vectors
:type y: list
:param K: The number of nearest neighbors to consider in classification
:type K: int
:param kfold: The number of folds in the CV
:type kfold: int
:param selectKBest: The number of best features to select
:type selectKBest: int
:return: An array of predicted classes
"""
try:
# Prepare data
X, y = numpy.array(X), numpy.array(y)
# Define classifier
clf = neighbors.KNeighborsClassifier(n_neighbors=K)
# Select K Best features if enabled
X_new = SelectKBest(chi2, k=selectKBest).fit_transform(X, y) if selectKBest > 0 else X
predicted = cross_val_predict(clf, X_new, y, cv=kfold).tolist()
except Exception as e:
prettyPrintError(e)
return []
return predicted
评论列表
文章目录