python TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('S32')

参考:

TypeError: ufunc 'add' did not contain a loop with signature matching types:

http://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-a-loop-with-signature-matching-types

numpy数据类型dtype转换:http://www.mamicode.com/info-detail-1180317.html


#############################################################################


今天使用python实现kNN算法时遇到一个问题:


	#print "dataSet.shape : {}, type : {}, dtype: {}".format(dataSet.shape, type(dataSet), dataSet.dtype)
	#print "da.shape : {}, type : {}, dtype: {}".format(da.shape, type(da), da.dtype)
	dataSetSize = dataSet.shape[0]
	tempSet = np.tile(da, (dataSetSize, 1))
	#print "tempSet.shape : {}".format(tempSet.shape)
	diff = np.array(dataSet) - tempSet
其中dataSet,data变量的type类型均为numpy.ndarray,dataSet的大小为[10, 20],data的大小为[1, 20]

我的目的就是把data矩阵扩展到和dataSet相同大小后进行矩阵相减操作,但在最后一步出错:

TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('S32')


这让我一头雾水,网上查找中发现了关键字dtype

import numpy as np
arr = np.ones((2,2))
help(arr.dtype)



简而言之,dtype就是数组元素的数据类型。上面的错误表示相减的两个数组的dtype可能不同,所以我就打印了这两个数组的dtype。发现确实如此,一个是'S32',而另一个是'float64'。解决方法就是将dtype转换为'float64'


在网上找到,转换dtype需要使用函数astype:



示例程序:

import numpy as np
 
x = np.array([1, 2, 2.5])
x.astype(int)

y = np.array([3, 6, 2], dtype='S32')
y = y.astype('float64')

x - y



所以,在上面算法中加入

dataSet = dataSet.astype('float64')
欧了

这个错误通常是由于版本不兼容或参数类型不匹配引起的。根据引用的错误信息,报错的具体位置是在运行train.py程序时出现了TypeError: No loop matching the specified signature and casting was found for ufunc greater的错误。根据引用提供的临时解决方法,可以尝试去掉np.greater的dtype参数,即将代码中的np.greater(counts, 0)改为np.greater(counts, 0, dtype=bool)来解决该问题。另外,根据引用提供的代码案例,可以参考使用np.greater函数的正确用法来检查参数类型是否正确。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [YOLOv5训练自己的数据集(踩坑记录&自学用&不定期更新)](https://blog.csdn.net/weixin_53344432/article/details/130201898)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [No loop matching the specified signature and casting was found for ufunc greater](https://blog.csdn.net/jacke121/article/details/128414592)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值