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)

python TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('S32')_第1张图片


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


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

python TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('S32')_第2张图片


示例程序:

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

python TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('S32')_第3张图片


所以,在上面算法中加入

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

你可能感兴趣的:(python,python,numpy,dtype)