Nearest neighbors

Download Report

Transcript Nearest neighbors

Pattern Recognition
Nearest neighbors
2014. 10. 31
Hyunki Hong
Contents
• Nearest neighbors density estimation
• The k nearest neighbors classification rule
• k-NN as a lazy learner
• Characteristics of the kNN classifier
• Optimizing the kNN classifier
Non-parametric density estimation:
review
• the general expression for non-parametric density
estimation is
• At that time, we mentioned that this estimate could be
computed by
– Fixing 𝑉 and determining the number 𝑘 of data points inside 𝑉.
→ This is the approach used in kernel density estimation.
- Fixing 𝑘 and determining the minimum volume 𝑉 that
encompasses 𝑘 points in the dataset.
→ This gives rise to the k-nearest-neighbors (kNN)
approach.
K-NN density estimation
• Approach
– In k-NN we grow the volume surrounding the estimation
point 𝑥 until it encloses a total of k data points
– The density estimate then becomes.
where 𝑅𝑘𝐷(𝑥) : the distance between the estimation point 𝑥 and its 𝑘th closest neighbor
𝑐𝐷 : the volume of the unit sphere in 𝐷 dimensions,
which is equal to
Thus 𝑐1 = 2, 𝑐2 = 𝜋, 𝑐3 = 4𝜋/3, and so on.
cf. z>-1일 때,
특히, 자연수 +0.5꼴에서는
• In general, the estimates that can be obtained with the
k-NN method are not very satisfactory.
- The estimates are prone to local noise.
- The method produces estimates with very heavy tails.
- Since the function 𝑅𝑘(𝑥) is not differentiable, the density
estimate will have discontinuities.
- The resulting density is not a true probability density since
its integral over all the sample space diverges.
• To illustrate the behavior of kNN we generated several
density estimates for a bimodal Gaussian: 𝑝(𝑥)=½𝑁
(0,1)+½𝑁(10,4).
kNN in action
• Example 1
– Three-class 2D problem with non-linearly
separable, multimodal likelihoods.
– We use the kNN rule (𝑘 = 5) and the Euclidean
distance.
– The resulting decision boundaries and decision
regions are shown below.
kNN in action
• Example 2
– In 2D, 3-class problem with unimodal
likelihoods with a common mean; these
classes are also not linearly separable.
– We used the kNN rule (𝑘 = 5), and the
Euclidean distance as a metric.
Characteristics of the kNN classifier
• Advantages
– Analytically tractable
– Simple implementation
– Uses local information, which can yield highly adaptive behavior
– Lends itself very easily to parallel implementations
• Disadvantages
– Large storage requirements
– Computationally intensive recall
– Highly susceptible to the curse of dimensionality
• 1NN versus kNN
– The use of large values of 𝑘 has two main advantages.
1. Yields smoother decision regions
2. Provides probabilistic information, i.e., the ratio of examples for each
class gives information about the ambiguity of the decision.
– However, too large a value of 𝑘 is detrimental.
1. It destroys the locality of the estimation since farther examples are
taken into account.
2. In addition, it increases the computational burden.
Improving the NN search procedure
• The NN search procedure can be stated as follows.
– Given a set of 𝑁 points in 𝐷-dimensional space and an
unlabeled example 𝑥𝑢 ∈ ℜ𝐷, find the point that minimizes the
distance to 𝑥𝑢.
– The naive approach of computing a set of 𝑁 distances, and
finding the (𝑘) smallest becomes impractical for large values
of 𝑁 and 𝐷.
• Two classical algorithms can be used to speed up the NN
search.
– Bucketing [Welch 1971]
1. The space is divided into identical cells; for each cell,
the data points inside it are stored in a list.
2. Cells are examined in order of increasing distance from
the query point; for each cell, the distance is computed between
its internal data points and the query point.
3. The search terminates when the distance from the query point to
the cell exceeds the distance to the closest point already visited.
Improving the NN search procedure
– k-d trees [Bentley, 1975; Friedman et al, 1977]
1. A k-d tree is a generalization of a binary search tree in high
dimensions.
a. Each internal node in a k-d tree is associated with a hyperrectangle and a hyper-plane orthogonal to one of the coordinate
axis.
b. The hyper-plane splits the hyper-rectangle into two parts, which
are associated with the child nodes.
c. The partitioning process goes on until the # data points in the
hyper-rectangle falls below some given threshold.
2. k-d trees partition the sample space according to the underlying
distribution of the data: the partitioning being finer in regions where
the density of data points is higher.
a. For a given query point, the algorithm works by first descending
the tree to find the data points lying in the cell that contains the
query point.
b. Then it examines surrounding cells if they overlap the ball
centered at the query point and the closest data point so far.
k-d tree example
• Data structure (3D case)
• Partitioning (2D case)
K-근접이웃 분류기
K-근접이웃 분류기
비모수적 확률밀도 추정과 최근접이웃 분류기
K-근접이웃(K-NN) 분류기
K-NN 분류기와 비모수적 밀도 추정
K-근접이웃 분류기의 특
성 결정 경계 설계 고려사항
매트랩을 이용한 K-NN 분류기 실
험
K-근접이웃 분류기
1) 비모수적 확률밀도 추정
각 클래스 Ci에 대한 확률밀도함수 (부피 V를 x의 함수, 데이터 수는 K로 고정)
N: 표본의 총개수
Vi(x) : 클래스 Ci에 속하는 데이터 중에서 x에서 K
번째로 가까운 데이터 xiK까지의 거리 d(x, xiK)
를 반경 ri(x)으로 하는 초구(hypersphere)
vn : n차원 입력공간상의 단위구의 체
적
: 결정규칙
2) 최근접이웃 분류기
C2
K = 1인 경우, 주어진 데이터 x에
대해 각 클래스별로 가장 가까운
데이터까지의 거리 계산
r1 x
r2
C1
클래스와 상관없이 모든 데이터 중에서 가장
작은 거리값을 갖는 데이터의 클래스로 할당
최근접이웃 분류기(Nearest Neighbor Classifier)
3) 최근접이웃 분류기의 수행 단계
1. 주어진 데이터 x와 모든 학습 데이터 {x1, x2, …, xN}와의 거리 계산
2. 거리가 가장 가까운 데이터를 찾아서 xmin으로 설정
3. xmin이 속하는 클래스에 할당.
즉, y(xmin)과 같은 값을 가지도록 y(x)를 결정
4) 최근접이웃 분류기의 문제-과다적합
학습 – 베이지안 분류기
테스트 – 베이지안 분류기
6.5%
학습 – 최근접이웃 분류기
테스트 - 최근접이웃분류기
13.5%
과다정합된
결정경계
 “K-근접이웃 분류기”
5) K-근접이웃 분류기
K-NN 분류기의 수행 단계
1. 주어진 데이터 x와 모든 학습 데이터 {x1, x2, …, xN}와의 거리 계산
2. 거리가 가장 가까운 것부터 순서대로 K개의 데이터를 찾아 후보 집합
N(x)={x1, x2,…, xK}를 생성
3. 후보 집합의 각 원소가 어떤 클래스에 속하는지 그 라벨값 y(x1),
y(x2), …, y(xK)을 찾음.
4. 찾아진 라벨 값 중 가장 많은 빈도수를 차지하는 클래스를 찾아 x를
그 클래스에 할당
6) K-NN 분류기와 비모수적 밀도 추정
K = 1인 경우, K-NN 분류기는 최근접이웃분류기와 동일 처리.
데이터 x 주어지면, 클래스와 상관없이 전체 데이터에서 K 개 만큼을
포함하는 영역의 부피 V(x)를 찾음.
VK(x) : K개의 데이터를 포함하는 영역의
부피
K1, K2, … , KM : VK(x) 내에 포함된
각 클래스별 데이터의 개수
C2
K=5인 경우
V5 ( x)
K2  3
K1  2
x
C1
y( x)  arg max{K1 ( x), K2 ( x)}  C2
2. K-근접이웃 분류기의 특성
1) K-NN 분류기의 결정경계
- 비선형적 결정경계
- 비모수적 방법에 기반하므로 데이터 분포 형태에 따라 성능 영
향 적음.
C1
C2
최소거리 분류기
K-근접이웃 분류기
2) K-근접이웃 분류기의 결정경계
데이터 분포가 복잡한 비선형 구조를 가지는 경우
8
7
8
C1
C2
7
6
6
5
5
4
4
3
3
2
2
1
1
0
0
1
2
3
4
5
6
가우시안 베이즈 분류기
실패
7
0
8 0
C1
1
C2
2
3
4
5
6
K-근접이웃 분류기
성공
7
8
3) 분류기의 비교
 가우시안 베이즈 분류기
 모수적 밀도 추정 방법에 기반
 학습 데이터를 통해 평균과 표준편차 계산
 분류 과정에서 학습 데이터가 불필요
 K-근접이웃 분류기
 비모수적 밀도 추정 방법에 기반
 새 데이터가 주어질 때마다 학습 데이터 전체와의 거리 계산으
로 K 개의 이웃 데이터 선정 필요함.
 항상 학습 데이터 저장  비용(계산량, 메모리) 문제 초래
4) K-NN 분류기의 설계 고려사항
노이즈에
과다정합
K=1
K=5
K값에 따른 결정경계의 변화
K=20
K=100
5) K-NN 분류기의 설계 고려사항
 적절한 K 값의 결정
 K = 1  바로 이웃한 데이터에만 의존하여 클래스가 결정. 노이
즈에 민감
 K >> 1  주어진 데이터 주변 영역이 아닌 전체 데이터 영역에서
각 클래스가 차지하는 비율(선험확률)에 의존
 주어진 데이터의 분포 특성에 의존
 데이터를 활용한 분류를 통해 가장 좋은 성능을 주는 값을 선택
6) K-NN 분류기의 설계 고려사항

거리함수 :
주어진 데이터와 학습 데이터간의 거리 계산
유클리디안 거리
(2차 노름)
1차 노름
p차 노름
내적
코사인 거리
정규화된
유클리디안 거리
마할라노비스 거리
각 좌표축 방향으로의 분산 차이를 고려하여 반영
K-NN 분류기 실험
1) 데이터 생성 및 실험 결과
5
4
C3
C2
3
2
1
0
학습 데이터: 100개/클래스
-1
C1
-2
-2
테스트 데이터: 105개/클래스
-1
0
1
2
3
4
5
K-근접이웃 분류기의 분류 결과 (%)
K=1
K=5
K=10
K=50
학습오차
0.00
9.67
11.67
11.67
테스트 오차
14.74
11.11
10.46
10.52
2) K-NN 분류기
load dataCh4_7
%학습 데이터 로드
X=[X1;X2;X3];
Etrain=0;
N = size(X,1);
for i=1:N
x=X(i,:);
% 각 데이터에 대해 분류시작
for j=1:N
% 모든 데이터와의 거리 계산
d(j,1)=norm(x-X(j,:));
end
[sx,si]=sort(d);
% 거리순으로 정렬
K=5; c=zeros(3,1);
% K=5로 정함
for j=1:K
% 이웃한 K개 데이터의 라벨을
if (si(j)<=100) c(1)=c(1)+1; end % 점검하여 투표수행
if (si(j)>200) c(3)=c(3)+1; end
if ((si(j)>100) & (si(j)<=200)) c(2)=c(2)+1; end
end
[maxv, maxi]=max(c);
% 최대 투표수를 받은 클래스로 할당
if (maxi~=(floor((i-1)/100)+1))
% 원래 클래스 라벨과 다르면
Etrain(1,1) = Etrain(1,1)+1;
% 오류데이터의 개수를 증가
end;
end
Error_rate = Etrain/N;
%오분류율 출력
3) K값에 따른 결정경계의 변화
K=1
K=5
K=10
K=50
베이즈 분류기는 적절한 확률 모델 추정, K-NN은 적절한 K 찾는 것 중요
4) 결정경계 그리기
load dataCh4_7
%학습 데이터 로드
X=[X1;X2;X3];
[x,y]=meshgrid([-2.5:0.1:5.5],[-2.5:0.1:5.5]);
%입력공간전체의 데이터준비
XY=[x(:), y(:)];
plot(X1(:,1), X1(:,2), '*'); hold on;
%학습데이터 그리기
plot(X2(:,1), X2(:,2), 'ro'); plot(X3(:,1), X3(:,2), 'kd');
for i=1:size(XY,1)
%전제 입력공간의 데이터에 대해
xt=XY(i,:);
%클래스 라벨을 결정
for j=1:size(X,1)
d(j,1)=norm(xt-X(j,:));
end
[sx,si]=sort(d);
K=1; c=zeros(3,1);
for j=1:K
if (si(j)<=100) c(1)=c(1)+1; end
if (si(j)>200) c(3)=c(3)+1; end
if ((si(j)>100) & (si(j)<=200)) c(2)=c(2)+1; end
end
[maxv, maxi]=max(c);
rxy1(i,1)=maxi;
end
rxy1=reshape(rxy1,size(x));
contour(x, y,rxy1);
%클래스 라벨에 따른 등고선 그리기
axis([-2.5 5.5 -2.5 5.5]); grid on
K – NNR(Nearest Neighbor Rule) 밀도 추정
• k개의 최근접하는 이웃을 이용
– 라벨이 없는 임의의 입력 데이터 Xu를 학습된 데이터 클래스로 분류
• 주어진 학습 데이터 집합들에 속하는 k개의 가장 가까운 표본을 찾아낸
다음,
• k개의 부분집합 내에 가장 많은 빈도를 클래스로 Xu를 할당
– k-NNR의 필요데이터
• 상수 k
• 라벨이 있는 학습 데이터
집합의 표본
• 거리 척도
k = 5 인 경우
: Xu는 ω1로 할당
k – NNR을 이용한 밀도 추정
• k-NNR을 이용한 결정경계 추정
– K = 5로 가정하고 세 클래스에 대한 경계 추정을 수행한 결과.
비선형적 결정경계 가능
k – NNR을 이용한 밀도 추정
R(x) = k개의 근접 데이터와 기준점 x사이의 거리
• k-NNR을 이용한 밀도
추정 예
C = D차원의 영역 (즉, D차원 구의 체적)
D
cf. z>-1일 때,
특히, 자연수 +0.5꼴에서는
k – NNR을 이용한 밀도 추정
• k-NNR을 이용한 밀도 추정 예
k – NNR을 이용한 밀도 추정
비모수 밀도 추정을 이용한 패턴 인식
– 각 클래스에 대한 우도확률 추정하고 베이즈 결정 규칙 이용해
시험 데이터 분류 → 가장 큰 사후 확률의 클래스 선택
– Non-parametric approach의 장점
• 패턴 인식 접근의 용이성, 사전 지식 불필요, unimodal/bimodal 폭
넓게 적용 가능 등…
– 단점
• 정확한 추정을 하려면 매우 많은 수의 표본 데이터가 주어져야 함.
• 많은 계산 시간 및 고용량의 메모리 요구
– K-NNR을 이용한 패턴 인식의 예
• N개의 학습 표본 집합 {x1, x2, …, xN}이 c개의 부분집합 D1, D2, … ,
DC 로 분포하고, 각 부분 집합 Dj 는 클래스 ωj 에 속한다고 가정
• 입력 표본값 x가 주어졌을 때 어느 클래스로 분류되는지 인식 과정
비모수 밀도 추정을 이용한 패턴 인식
– Non-parametric Density Estimation(K-NNR) 이용한 패
턴 인식 예
• N개의 학습 표본 집합 {x1, x2, …, xN}이 c개의 부분집합 D1, D2, …,
DC 로 분포하고, 각 부분 집합 Dj 는 클래스 ωj 에 속한다고 가정
• 입력 표본값 x가 주어졌을 때 어느 클래스로 분류되는지 인식하는
과정. 즉, 사후확률 P(ωj |x) 계산 과정
1) 우도함수 (likelihood function) 추정
– 클래스 ωj 에서 k-NNR 판별조건에 맞는 표본의 수가 kj일 때, 결합확률 P( X ,  j )
의 일반형을 이용하여 우도를 다음과 같이 가정할 수 있음.
kj
kj
pN ( X ,  j ) 
 pN ( X |  j ) 
NV
NV
pN ( X ,  j )
kj
kj
P( j | X )  c
 c 
2) 사후확률(posterior) 추정
 pN ( X , i )  ki k
3) 최종 클래스 결정
i 1
P(P | X )  max j P( j | X )
i 1