Python3 TypeError: only size-1 arrays can be converted to Python scalars

问题:在用python3使用knn.train(trainData, responses)的时候,可能会产生错误:TypeError: only size-1 arrays can be converted to Python scalars

newcomer = np.random.randint(0, 100, (1, 2)).astype(np.float32)
plt.scatter(newcomer[:, 0], newcomer[:, 1], 80, 'g', 'o')
knn = cv2.ml.KNearest_create()
knn.train(trainData, responses)

报错信息:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in ()
      2 plt.scatter(newcomer[:, 0], newcomer[:, 1], 80, 'g', 'o')
      3 knn = cv2.ml.KNearest_create()
----> 4 knn.train(trainData, responses)
      5 

TypeError: only size-1 arrays can be converted to Python scalars

解决:将knn.train(trainData, responses)替换为:

              knn.train(trainData, cv2.ml.ROW_SAMPLE, responses)

分析:

        在python3中,knn.train需要传入layout参数,如第二种构造方法

Docstring:
train(trainData[, flags]) -> retval
.   @brief Trains the statistical model
.   
.   @param trainData training data that can be loaded from file using TrainData::loadFromCSV or
.   created with TrainData::create.
.   @param flags optional flags, depending on the model. Some of the models can be updated with the
.   new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP).


train(samples, layout, responses) -> retval
.   @brief Trains the statistical model
.   
.   @param samples training samples
.   @param layout See ml::SampleTypes.
.   @param responses vector of responses associated with the training samples.
Type:      builtin_function_or_method

变更样例:

knn.train(trainData, cv2.ml.ROW_SAMPLE, responses)

参考文章:http://www.itkeyword.com/doc/6947006191723413x615/knn-train-in-cv2-with-opencv-3-0

说明:问题产生的环境
           Python版本:3.6.5
           OpenCV版本:3.4.2

转自:https://blog.csdn.net/yuxuan_08/article/details/87966958

你可能感兴趣的:(Python3 TypeError: only size-1 arrays can be converted to Python scalars)