Python3|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)
报错信息:
---------------------------------------------------------------------------
TypeErrorTraceback (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
【Python3|Python3 TypeError: only size-1 arrays can be converted to Python scalars】转自:https://blog.csdn.net/yuxuan_08/article/details/87966958
推荐阅读
- Python3|Python3 MySQL 数据库连接
- win10环境|win10环境 python3.6安装pycrypto-2.6.1的问题
- 分布式|《Python3网络爬虫开发实战(第二版)》内容介绍
- 由Uncaught|由Uncaught TypeError: this.player.startMoveAt is not a function引申
- python3|python3 模块 包
- Python|Python TypeError: 'module' object is not callable 原因分析
- Python3.x(Socket网络编程)
- 树莓派|树莓派 | 04 安装基于python3.5的tensorflow,解决python版本不匹配问题
- ubuntu下安装python3.6及以上版本出现pip3报错等问题
- python实现gui编程_怎样用Python3实现GUI编程()