在 Sklearn 中通过一维数组获取弃用警告

Getting deprecation warning in Sklearn over 1d array

不幸的是,我在解决 中描述的警告问题时遇到了糟糕的时间,按照此处建议的修复方法,我的问题没有得到解决。

显然我正在将一维数组输入 SVM.SVC predict 并且我收到了弃用警告。我只是不知道我做错了什么,我希望有人能帮助我修复我的代码。我确定这是我遗漏的一个小修正。

我正在使用 Python 2.7

我从一个数据框开始 data_df(为清楚起见,此处缩小了尺寸,但代码和结构是准确的):

   Price/Sales  Price/Book  Profit Margin  Operating Margin
0         2.80        6.01          29.56             11.97
1         2.43        4.98          25.56              6.20
2         1.61        3.24           4.86              5.38
3         1.52        3.04           4.86              5.38
4         3.31        4.26           6.38              3.58

我将数据帧更改为 numpy 数组:

X = data_df.values

这给了我:

[[  2.8,    6.01,  29.56,  11.97],
 [  2.43,   4.98,  25.56,   6.2 ],
 [  1.61,   3.24,   4.86,   5.38],
 [  1.52,   3.04,   4.86,   5.38],
 [  3.31,   4.26,   6.38,   3.58]]

然后我将我的数据居中并归一化:

X = preprocessing.scale(X)

这给我:

[[ 0.67746872  1.5428404   1.39746257  1.90843628]
 [ 0.13956437  0.61025495  1.03249454 -0.10540376]
 [-1.05254797 -0.96518067 -0.85621499 -0.3915994 ]
 [-1.18338957 -1.14626523 -0.85621499 -0.3915994 ]
 [ 1.41890444 -0.04164945 -0.71752714 -1.01983373]]

我的 y 是一系列 0 和 1:

[0, 0, 1, 0, 1]

实际数据集大约有 10,000 个观察值。我使用以下代码对 select 个子集进行训练、测试和检查准确性:

test_size = 500


clf = svm.SVC(kernel = "linear", C=1.0)
clf.fit(X[:-test_size],y[:-test_size])

correct_count = 0

for x in range(1, test_size+1):
    if clf.predict(X[-x])[0] == y[-x]:
        correct_count += 1

print("Accuracy: ", correct_count / test_size * 100.00)

我输入 clf.predict 的因子测试集(X[-x] for x = 1 to test_size +1)抛出以下警告:

C:\Users\me\AppData\Local\Continuum\Anaconda2\lib\site-packages\sklearn\ut
ils\validation.py:386: DeprecationWarning: Passing 1d arrays as data is deprecat
ed in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.re
shape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contain
s a single sample.
  DeprecationWarning)

代码有效,我确实得到了预测并且能够计算准确性,但我仍然发出警告。

据我从搜索和上面提到的其他问题中可以看出,我的数据格式正确。我错过了什么?

在此先感谢您的帮助。

您只需要按照警告消息的建议进行即可。您的变量 X[-x] 是一维的,但需要是二维的。这是一个具有多个特征的样本,因此只需向其中添加 .reshape(1,-1) 即可清除警告:

for x in range(1, test_size+1):
    if clf.predict(X[-x].reshape(1,-1))[0] == y[-x]:
        correct_count += 1

clf.predict 函数能够使用多个特征预测多个值。如果您传入一维数组,则不清楚您的意图是具有多个特征的单个值,还是具有单个特征的多个值。警告消息要求您自己形成二维数组以明确区分。