回答
在多元數據中,如果變量之間存在協方差(,即您的案例X,Y,Z中的),則歐幾里德距離將失敗。
因此,什麼馬氏距離所做的是,
它把變量到不相關的空間。
使每個變量varience等於1
然後計算簡單的歐氏距離。
我們可以計算出馬氏距離對於每個數據樣本如下,
在這裏,我已經提供了Python代碼並添加註釋,以便您可以理解的代碼。
import numpy as np
data= np.matrix([[1, 2, 3, 4, 5, 6, 7, 8],[1, 4, 9, 16, 25, 36, 49, 64],[1, 4, 9, 16, 25, 16, 49, 64]])
def MahalanobisDist(data):
covariance_xyz = np.cov(data) # calculate the covarince matrix
inv_covariance_xyz = np.linalg.inv(covariance_xyz) #take the inverse of the covarince matrix
xyz_mean = np.mean(data[0]),np.mean(data[1]),np.mean(data[2])
x_diff = np.array([x_i - xyz_mean[0] for x_i in x]) # take the diffrence between the mean of X variable the sample
y_diff = np.array([y_i - xyz_mean[1] for y_i in y]) # take the diffrence between the mean of Y variable the sample
z_diff = np.array([z_i - xyz_mean[2] for z_i in z]) # take the diffrence between the mean of Z variable the sample
diff_xyz = np.transpose([x_diff, y_diff, z_diff])
md = []
for i in range(len(diff_xyz)):
md.append(np.sqrt(np.dot(np.dot(np.transpose(diff_xyz[i]),inv_covariance_xyz),diff_xyz[i]))) #calculate the Mahalanobis Distance for each data sample
return md
def MD_removeOutliers(data):
MD = MahalanobisDist(data)
threshold = np.mean(MD) * 1.5 # adjust 1.5 accordingly
outliers = []
for i in range(len(MD)):
if MD[i] > threshold:
outliers.append(i) # index of the outlier
return np.array(outliers)
print(MD_removeOutliers(data))
希望這會有所幫助。
引用,
我無法找到有MahalanobisDist的圖書館,請告訴圖書館。如果你解釋它會很有幫助。 –
我編輯答案 –
真棒答案!現在你能告訴我爲什麼openCv的Mahalanobis要求多組數據? (DATA1,DATA2,inverted_covariance) –
- 1. 馬氏距離
- 2. 計算馬氏距離
- 3. 每對觀測值的馬氏距離
- 4. 用C#計算馬氏距離
- 5. K-手段和馬氏距離
- 6. 一維馬氏距離在Python
- 7. 歐氏距離
- 8. 歐氏距離
- 9. 歐氏距離
- 10. 編輯距離 - 隨着記憶
- 11. 矩陣(mxn)的馬氏距離m << n
- 12. 如何去除隨機邊距?
- 13. Python:如何計算常規網絡的歐氏距離分佈?
- 14. 使用字數計算歐氏距離
- 15. Excel公式爲歐氏距離
- 16. 用numpy計算歐氏距離
- 17. 計算KNN的歐氏距離
- 18. 隨着IBM JDK8看到sun.io.UnknownCharacterException異常
- 19. 從距離閾值距離更近的雲中移除點
- 20. 隨着距離的增加,精靈的顏色發生變化
- 21. Sqllite:隨着時間的推移發現異常值
- 22. 刪除多元離羣值mvoutlier
- 23. 如何使用IQR方法去除/消除異常值
- 24. 如何去除R中指定值以上的異常值?
- 25. AWK:隨着值
- 26. 亨利馬烏:正火UserSimilarity距離
- 27. Alexa的距離的NodeJS亞馬遜LAMBDA
- 28. 意味着排除使用dplyr的異常值
- 29. 隨着靜態值插入多行
- 30. 情況,即隨着多個值
馬哈拉諾比斯距離適用於IID數據(見[此信息以供異常檢測](HTTP: //kldavenport.com/mahalanob是距離 - 和 - 離羣/))。但是你的數據不是iid。 – Maxim