거리 기반 학습

Python으로 설계하는 Machine Learning 워크플로

Dr. Chris Anagnostopoulos

Honorary Associate Professor

거리와 유사도

from sklearn.neighbors import DistanceMetric as dm
dist = dm.get_metric('euclidean')

X = [[0,1], [2,3], [0,6]] dist.pairwise(X)
array([[0.        , 2.82842712, 5.        ],
       [2.82842712, 0.        , 3.60555128],
       [5.        , 3.60555128, 0.        ]])
X = np.matrix(X)
np.sqrt(np.sum(np.square(X[0,:] - X[1,:])))
2.82842712
Python으로 설계하는 Machine Learning 워크플로

비유클리드 LOF (Local Outlier Factor)

clf = LocalOutlierFactor(
    novelty=True, metric='chebyshev')
clf.fit(X_train)
y_pred = clf.predict(X_test)
dist = dm.get_metric('chebyshev')
X = [[0,1], [2,3], [0,6]]
dist.pairwise(X)
array([[0., 2., 5.],
       [2., 0., 3.],
       [5., 3., 0.]])

검은 점 두 클러스터와 떨어진 빨간 점들.

Python으로 설계하는 Machine Learning 워크플로

모든 메트릭이 비슷할까?

해밍 거리 행렬:

dist = dm.get_metric('hamming')
X = [[0,1], [2,3], [0,6]]
dist.pairwise(X)
array([[0. , 1. , 0.5],
       [1. , 0. , 1. ],
       [0.5, 1. , 0. ]])
Python으로 설계하는 Machine Learning 워크플로

모든 메트릭이 비슷할까?

from scipy.spatial.distance import pdist

X = [[0,1], [2,3], [0,6]] pdist(X, 'cityblock')
array([4., 5., 5.])
from scipy.spatial.distance import \ 
    squareform
squareform(pdist(X, 'cityblock'))
array([[0., 4., 5.],
       [4., 0., 5.],
       [5., 5., 0.]])
Python으로 설계하는 Machine Learning 워크플로

실제 예시

Hepatitis 데이터셋:

   Class   AGE  SEX  STEROID    ...      
0    2.0  40.0  0.0      0.0    ...      
1    2.0  30.0  0.0      0.0    ...      
2    1.0  47.0  0.0      1.0    ...      
1 https://archive.ics.uci.edu/ml/datasets/Hepatitis
Python으로 설계하는 Machine Learning 워크플로

실제 예시

유클리드 거리:

squareform(pdist(X_hep, 'euclidean'))
[[  0.  127.   64.1]
 [127.    0.  128.2]
 [ 64.1 128.2   0. ]]
  • 1의 최근접은 3: 잘못된 클래스

해밍 거리:

squareform(pdist(X_hep, 'hamming'))
[[0.  0.5 0.7]
 [0.5 0.  0.6]
 [0.7 0.6 0. ]]
  • 1의 최근접은 2: 올바른 클래스
Python으로 설계하는 Machine Learning 워크플로

더 큰 도구 상자

Python으로 설계하는 Machine Learning 워크플로

Preparing Video For Download...