python numpy成对编辑距离
因此,我有一个numpy字符串数组,我想使用以下函数计算每对元素之间的成对编辑距离:scipy.spatial.distance.pdist from 我的数组示例如下所示:python numpy成对编辑距离,python,numpy,scipy,lambda,pdist,Python,Numpy,Scipy,Lambda,Pdist,因此,我有一个numpy字符串数组,我想使用以下函数计算每对元素之间的成对编辑距离:scipy.spatial.distance.pdist from 我的数组示例如下所示: >>> d[0:10] array(['TTTTT', 'ATTTT', 'CTTTT', 'GTTTT', 'TATTT', 'AATTT', 'CATTT', 'GATTT', 'TCTTT', 'ACTTT'], dtype='|S5') 但是,由于它没有“editdistance
>>> d[0:10]
array(['TTTTT', 'ATTTT', 'CTTTT', 'GTTTT', 'TATTT', 'AATTT', 'CATTT',
'GATTT', 'TCTTT', 'ACTTT'],
dtype='|S5')
但是,由于它没有“editdistance”选项,因此,我想提供一个自定义的距离函数。我尝试了这一点,但遇到了以下错误:
>>> import editdist
>>> import scipy
>>> import scipy.spatial
>>> scipy.spatial.distance.pdist(d[0:10], lambda u,v: editdist.distance(u,v))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/epd-7.3.2/lib/python2.7/site-packages/scipy/spatial/distance.py", line 1150, in pdist
[X] = _copy_arrays_if_base_present([_convert_to_double(X)])
File "/usr/local/epd-7.3.2/lib/python2.7/site-packages/scipy/spatial/distance.py", line 153, in _convert_to_double
X = np.double(X)
ValueError: could not convert string to float: TTTTT
导入editdist
>>>进口西皮
>>>导入scipy.spatial
>>>空间距离pdist(d[0:10],λu,v:editdist.distance(u,v))
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
pdist中的文件“/usr/local/epd-7.3.2/lib/python2.7/site packages/scipy/spatial/distance.py”,第1150行
[十] =\u复制\u数组\u如果\u基本\u存在([\u转换\u到\u双(X)])
文件“/usr/local/epd-7.3.2/lib/python2.7/site packages/scipy/spatial/distance.py”,第153行,在转换为双精度
X=np.double(X)
ValueError:无法将字符串转换为浮点:TTT
如果确实必须使用
pdist
,则首先需要将字符串转换为数字格式。如果您知道所有字符串的长度都相同,那么可以很容易地做到这一点:
numeric_d = d.view(np.uint8).reshape((len(d),-1))
这只是将字符串数组视为uint8
字节的长数组,然后对其进行重塑,使每个原始字符串单独位于一行上。在您的示例中,这看起来像:
In [18]: d.view(np.uint8).reshape((len(d),-1))
Out[18]:
array([[84, 84, 84, 84, 84],
[65, 84, 84, 84, 84],
[67, 84, 84, 84, 84],
[71, 84, 84, 84, 84],
[84, 65, 84, 84, 84],
[65, 65, 84, 84, 84],
[67, 65, 84, 84, 84],
[71, 65, 84, 84, 84],
[84, 67, 84, 84, 84],
[65, 67, 84, 84, 84]], dtype=uint8)
然后,您可以像平常一样使用pdist
。只需确保您的editdist
函数需要整数数组,而不是字符串。通过调用.tostring()
,可以快速转换新输入:
def我的pdist(数据,f):
N=len(数据)
矩阵=np.空([N*(N-1)/2])
ind=0
对于范围(N)中的i:
对于范围(i+1,N)内的j:
矩阵[ind]=f(数据[i],数据[j])
ind+=1
返回矩阵
看起来不是为字符串设计的。您可能需要查看错误行是pdist
中的第二行。因此,在将字符串传递到pdist
之前,必须将字符串转换为某种数字。另外,pdist
需要一个2D数组。。。。或者直接在uint8
s上编辑距离。提供一些上下文,关于这是如何回答问题的附加信息,不仅对问题的原始提问者,而且对该解决方案的未来访问者都有帮助和益处。一个原始的“仅代码”片段并不是最好的答案形式。
def editdist(x, y):
s1 = x.tostring()
s2 = y.tostring()
... rest of function as before ...