【问题标题】:model.predict(sample) returning TypeError: cannot perform reduce with flexible typemodel.predict(sample) 返回 TypeError: 不能使用灵活类型执行 reduce
【发布时间】:2020-10-08 02:59:27
【问题描述】:

当我尝试基于拟合模型进行预测时,我一直遇到此错误。

training, testing = train_test_split(gesture, test_size = 0.2, random_state = 0)
x = training.drop('CLASS', axis = 1)                    # remove the Class column from Training dataframe
y = testing.drop('CLASS', axis = 1)                     # remove the Class column from Testing dataframe
f_train = x.values.tolist()
l_train = training['CLASS'].values.tolist()             # make a list of class identifiers from Training dataframe
f_test = y.values.tolist()

knn = KNeighborsRegressor(n_neighbors = 5)
knn.fit(f_train, l_train)
predictions = knn.predict(f_test)

上述代码最后一行出现错误,错误信息如下:

    Traceback (most recent call last):
  File "C:\Users\Umair Khan\Dropbox\`Shift betweeen PCs\Work\EMG Hand Gesture\Codes\ML_on_CSV.py", line 39, in <module>
    predictions = knn.predict(f_test)
  File "C:\Users\Umair Khan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sklearn\neighbors\_regression.py", line 185, in predict
    y_pred = np.mean(_y[neigh_ind], axis=1)
  File "<__array_function__ internals>", line 6, in mean
  File "C:\Users\Umair Khan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\numpy\core\fromnumeric.py", line 3335, in mean
    out=out, **kwargs)
  File "C:\Users\Umair Khan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\numpy\core\_methods.py", line 151, in _mean
    ret = umr_sum(arr, axis, dtype, out, keepdims)
TypeError: cannot perform reduce with flexible type

f_test 是类似[[16, 30, 35, 250, -1, 0.5, 35, 0.03, 0.02], [16, 30, 35, 250, -1, 0.5, 35, 0.03, 0.02]] 的列表列表

我也尝试在predict(sample) 中传递一个数组,但问题仍然存在。

predictions = knn.predict(np.array(f_test).astype(np.float))

【问题讨论】:

    标签: numpy machine-learning scikit-learn python-3.7


    【解决方案1】:

    已解决: 将 l_train 的 dtype 从 string 更改为 float 并且错误消失了。 f_trainf_test 已经是浮点类型。

    【讨论】:

      【解决方案2】:

      我们需要查看更多错误回溯。以及有关函数输入的信息,尤其是 shape 和 dtype。

      我在使用structured arrays 时看到了此错误消息。但这些可能出现在您的代码中的位置并不明显。

      In [15]: np.ones((2,), dtype='i,i')                                             
      Out[15]: array([(1, 1), (1, 1)], dtype=[('f0', '<i4'), ('f1', '<i4')])
      In [16]: np.sum(np.ones((2,), dtype='i,i'))                                     
      ....
      ---> 87     return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
           88 
           89 
      
      TypeError: cannot perform reduce with flexible type
      

      【讨论】:

      • f_trainf_test 是分别代表 1200 个样本和 300 个样本的 9 个特征的列表。而l_train 是一个包含 1200 个元素的列表。
      猜你喜欢
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 2017-09-12
      • 2014-02-23
      • 2015-04-08
      • 2020-10-03
      • 2013-12-02
      • 2014-05-07
      相关资源
      最近更新 更多