这是我用来解决信用卡欺诈检测分类问题的代码:
import pandas as pdfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import train_test_splitdf = pd.read_csv(r'C:\Users\SVISHWANATH\Downloads\creditcard.csv')f = df.drop(['Class'], axis = 1)g = df.Classg.values.reshape(-1,1)X_train, X_test, y_train, y_test = train_test_split(f, g, stratify = g)knn = KNeighborsClassifier(n_neighbors = 5)knn.fit(X_train, y_train)knn.predict(y_test)
不知为何,即使我指定了reshape参数,上述代码仍然导致错误。这是错误信息:
ValueError Traceback (most recent call last)<ipython-input-37-d24a7d3e9bd3> in <module> 12 knn = KNeighborsClassifier(n_neighbors = 5) 13 knn.fit(X_train, y_train)---> 14 knn.predict(y_test)~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\neighbors\_classification.py in predict(self, X) 171 Class labels for each data sample. 172 """--> 173 X = check_array(X, accept_sparse='csr') 174 175 neigh_dist, neigh_ind = self.kneighbors(X)~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\utils\validation.py in inner_f(*args, **kwargs) 71 FutureWarning) 72 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})---> 73 return f(**kwargs) 74 return inner_f 75 ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator) 622 "Reshape your data either using array.reshape(-1, 1) if " 623 "your data has a single feature or array.reshape(1, -1) "--> 624 "if it contains a single sample.".format(array)) 625 626 # in the future np.flexible dtypes will be handled like object dtypesValueError: Expected 2D array, got 1D array instead:array=[0 0 0 ... 0 0 0].Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
回答:
y_test是你试图预测的结果(即类别)。你需要从可用的数据中进行预测,即在分类时你会拥有的一切数据,除了类别之外:在你的例子中,这是X_test,所以你需要将knn.predict(y_test)
改为knn.predict(X_test)
。然后你可以使用y_test来比较你的预测结果,看看它们有多准确。