使用scikit-learn进行简单分类不工作

这是我用来解决信用卡欺诈检测分类问题的代码:

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来比较你的预测结果,看看它们有多准确。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注