티스토리 뷰

Study/Go Lang

[Go Lang] Mahalanobis Distance

Hoon's Blog 2019. 12. 18. 17:22

# Mahalanobis Distance?

Mahalanobis  Distance

 

# 개념에 대한 예시

- 마할라노비스 거리(Mahalanobis distance)는 평균과의 거리가 표준편차의 몇 배인지를 나타내는 값이다

(설명이 잘되어있어 링크만 올리도록함)

Ref. https://darkpgmr.tistory.com/41#rp

 

# 수식에 대한 예시

(설명이 잘되어있어 링크만 올리도록함)

Ref. http://www.joon.pe.kr/blog/82

 

위 예시에 의하면

A(0.5, 0.5), B(0, 1), C(1.5, 1.5) 일때, 

mahalanobis(A, B) = 5, mahalanobis(B, C) = 4가 된다. 

 

Go Lang으로 구현하여 확인해보자.

 

 

# Go Lang

// Mahalanobis project main.go
package main

import (
    "fmt"
    "math"
)

type covariance struct {
    w11, w12,
    w21, w22 float64
}

type horizontalMatrix struct {
    w11, w12 float64
}

type verticalMatrix struct {
    w11,
    w21 float64
}

func main() {

    matrixP1 := horizontalMatrix{w11: 0.5, w12: 0.5}
    matrixP2 := horizontalMatrix{w11: 0, w12: 1}
    matrixP3 := horizontalMatrix{w11: 1.5, w12: 1.5}

    fmt.Println("A <-> B : ", mahalanobis(matrixP1, matrixP2))
    fmt.Println("A <-> C : ", mahalanobis(matrixP1, matrixP3))
}

func mahalanobis(matrixP1, matrixP2 horizontalMatrix) float64 {

    cov := covariance{w11: 0.3, w12: 0.2, w21: 0.2, w22: 0.3}
    revCov := revCovariance(cov)

    //    fmt.Println(revCov.w11, revCov.w12)
    //    fmt.Println(revCov.w12, revCov.w22)

    matrixTmp := horizontalMatrix{(matrixP1.w11 - matrixP2.w11), (matrixP1.w12 - matrixP2.w12)}

    matrix := horizontalMatrix{
        w11: ((matrixTmp.w11 * revCov.w11) + (matrixTmp.w12 * revCov.w21)),
        w12: ((matrixTmp.w11 * revCov.w12) + (matrixTmp.w12 * revCov.w22))}

    return matrix.w11*matrixTmp.w11 + matrix.w12*matrixTmp.w12
}

func revCovariance(cov covariance) covariance {

    //    reverseMatrix(matrix(a, b, c, d)) = 1 / (ad - bc) * matrix(d, -b, -c, a)
    tmp := math.Round(1 / (cov.w11*cov.w22 - cov.w12*cov.w21))
    ret := covariance{w11: (tmp * cov.w22), w12: -(tmp * cov.w12), w21: -(tmp * cov.w21), w22: (tmp * cov.w11)}
    return ret
}

 

 

# 결과

결과 : mahalanobis(A, B) = 5, mahalanobis(B, C) = 4

'Study > Go Lang' 카테고리의 다른 글

[Go Lang] Web Server?  (0) 2019.12.18
[Go Lang] Euclidean Distance  (0) 2019.12.18
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함