[英]Hamming distance Matlab to Python
好的,我正在用k-NN方法對兩個文檔進行漢明距離。 我正在嘗試將Matlab代碼轉換為Python,但是我已經看了好幾個小時了,不知道是什么原因導致了錯誤。
Matlab中的代碼:
function [ Dist ] = hamming_distance( X,Xtrain )
% Function calculates Hamming distances of elements in set X from elements in set Xtrain. Distances of objects are returned as matrix Dist
% X - set of objects we are comparing N1xD
% Xtrain - set of objects to which X objects are compared N2xD
% Dist - matrix of distances between X and Xtrain objects N1xN2
% N1 - number of elements in X
% N2 - number of elements in Xtrain
% D - number of features (key words)
N1 = size(X,1);
N2 = size(Xtrain,1);
Dist = zeros(N1,N2);
D1 = size(X,2);
for i=1:N1
for j=1:N2
temp_matrix = xor(X(i,1:D1),Xtrain(j,1:D1));
Dist(i,j) = sum(temp_matrix);
end
end
end
到目前為止,這是我在Python中編寫的內容:
def hamming_distance(X, X_train):
"""
:param X: set of objects that are going to be compared N1xD
:param X_train: set of objects compared against param X N2xD
Functions calculates Hamming distances between all objects from set X and all object from set X_train.
Resulting distances are returned as matrices.
:return: Distance matrix between objects X and X_train X i X_train N1xN2
"""
N1 = X.shape[0]
N2 = X_train.shape[0]
hdist = np.zeros(shape =(N1, N2))
D1 = X.shape[1]
for i in range (1,N1):
for j in range (1, N2):
temp_matrix = np.logical_xor(X[i,1:D1], X_train[j, 1:D1])
hdist[i, j] = np.sum(temp_matrix)
return hdist
該錯誤似乎在Python代碼的xor部分中。 我不明白那里可能出什么事了; 我嘗試將其表示為(X[i,1:D1]) ^ (X_train[j, 1:D1])
但它沒有任何改變。 我檢查了logical_xor
函數,似乎我對該函數輸入正確。 我不知道錯誤是從哪里來的。 可能是因為矩陣形狀不同嗎? 我在調整大小時感到困惑,是否應該將X和X_train更改為數組? 我嘗試了一次,但沒有任何幫助。
錯誤:
Traceback (most recent call last):
File "C:\...\test.py", line 90, in test_hamming_distance
out = hamming_distance(data['X'], data['X_train'])
File "C:\...\content.py", line 28, in hamming_distance
temp_matrix = np.logical_xor(X[i,1:D1], X_train[j, 1:D1])
File "C:\...\Anaconda3\lib\site-packages\scipy\sparse\base.py", line 559, in __getattr__
raise AttributeError(attr + " not found")
AttributeError: logical_xor not found
我不能更改test.py,只能更改content.py。 Test.py應該工作正常,所以我確定我的函數有錯誤。 任何幫助,將不勝感激!
編輯:我有,在我的文件的頂部:
import numpy as np
寫numpy而不是np並沒有改變任何東西。 我收到錯誤消息'numpy wasn't defined'
。
之所以不起作用,是因為X
或X_train
都是稀疏稀疏矩陣。 Scipy稀疏矩陣尚不支持邏輯運算,盡管有關此運算的工作正在進行中 。
調用numpy函數時,此錯誤顯示在scipy中而不是numpy中的原因是, logical_xor
是numpy ufunc或“通用函數”。 旨在與numpy ufunc進行交互的Python類可以覆蓋ufunc的行為,而scipy稀疏矩陣可以避免調用不受支持的操作,這些操作會將數組轉換為密集數組,並可能耗盡所有內存。
您可能需要使用例如X.toarray()
將其轉換為密集數組。 如果太大而無法裝入內存,則應使用dask
或bcolz
類的軟件包為您處理內存管理。
編輯:稀疏稀疏矩陣不是ndarray的子類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.