【问题标题】:Simple classification using scikit-learn not working使用 scikit-learn 的简单分类不起作用
【发布时间】:2020-11-01 06:36:52
【问题描述】:

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

import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
df = pd.read_csv(r'C:\Users\SVISHWANATH\Downloads\creditcard.csv')
f = df.drop(['Class'], axis = 1)
g = df.Class
g.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 dtypes

ValueError: 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.

【问题讨论】:

    标签: machine-learning scikit-learn classification


    【解决方案1】:

    y_test 是您尝试预测的结果(即类)。您需要根据可用数据进行预测,即尝试分类时将拥有的数据,除了类之外的所有其他数据:在您的情况下是 X_test,因此您需要将 knn.predict(y_test) 更改为 knn.predict(X_test)。然后,您可以使用 y_test 比较您的预测并查看它们的准确度。

    【讨论】:

    • 谢谢!所以你会给出你想要预测的数据,我正确吗?
    • 是的。想象一下,如果您没有 X_test 和 y_test,并且想使用您的模型对某些数据进行分类。您可能拥有类似于 X_test 的数据,但由于您要做的是获取类,因此您将没有类信息(这就是 y_test)。所以你根据你拥有的信息进行预测,这类似于 X_test(或 X_train)。
    猜你喜欢
    • 2013-10-05
    • 2017-04-30
    • 1970-01-01
    • 2018-04-10
    • 2017-04-11
    • 2020-05-09
    • 2012-05-18
    • 2014-02-17
    相关资源
    最近更新 更多