Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Cửa sổ Parzen là một kỹ thuật ước tính mật độ không tham số. Ước tính mật độ trong nhận dạng mẫu có thể đạt được bằng cách sử dụng cách tiếp cận của các cửa sổ Parzen. Kỹ thuật ước tính mật độ cửa sổ Parzen là một loại khái quát hóa kỹ thuật biểu đồ. & NBSP; is a non-parametric density estimation technique. Density estimation in Pattern Recognition can be achieved by using the approach of the Parzen Windows. Parzen window density estimation technique is a kind of generalization of the histogram technique. 

Show

Nó được sử dụng để lấy hàm mật độ, & nbsp;. & Nbsp; được sử dụng để thực hiện phân loại Bayes. Khi chúng ta có một tính năng mẫu mới & nbsp; và khi cần phải tính toán giá trị của mật độ có điều kiện lớp, & nbsp; được sử dụng. & Nbsp; lấy giá trị dữ liệu đầu vào mẫu và trả về ước tính mật độ của mẫu dữ liệu đã cho. & NBSP;

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Hướng dẫn parzen-window classifier python - phân loại parzen-window python
is used to implement a Bayes Classifier. When we have a new sample feature 
Hướng dẫn parzen-window classifier python - phân loại parzen-window python
and when there is a need to compute the value of the class conditional densities, 
Hướng dẫn parzen-window classifier python - phân loại parzen-window python
is used. 
Hướng dẫn parzen-window classifier python - phân loại parzen-window python
takes sample input data value and returns the density estimate of the given data sample. 

Một hypercube n-chiều được coi là được giả định là sở hữu các mẫu dữ liệu k. & Nbsp; chiều dài của cạnh của hypercube được coi là hn. & Nbsp;
The length of the edge of the hypercube is assumed to be hn. 

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Do đó khối lượng của hypercube là: vn = hnd & nbsp;

Chúng tôi xác định hàm cửa sổ hypercube, (u) là hàm chỉ báo của hypercube đơn vị tập trung ở gốc .:&nbsφ(u) which is an indicator function of the unit hypercube which is centered at origin.: 
φ(u) = 1 if |ui| <= 0.5 
φ(u) = 0 otherwise 
Here, u is a vector, u = (u1, u2, …, ud)T
φ(u) should satisfy the following:

  1. Hướng dẫn parzen-window classifier python - phân loại parzen-window python
  2. Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Let 

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Vì, (u) được tập trung ở gốc, nó là đối xứng. & Nbsp; φ (u) = φ (-u) & nbsp; & nbsp;
φ(u) = φ(-u) 
 

Do đó, hàm mật độ ước tính là: & nbsp;

*** QuickLaTeX cannot compile formula:
 

*** Error message:
Error: Nothing to show, formula is empty

Ngoài ra, VN = HND, hàm mật độ trở thành: & nbsp;Vn = hnd, Density Function becomes : 

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Hướng dẫn parzen-window classifier python - phân loại parzen-window python
sẽ đáp ứng các điều kiện sau: & nbsp; & nbsp;

  1. Hướng dẫn parzen-window classifier python - phân loại parzen-window python
  2. Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Hướng dẫn parzen-window classifier python - phân loại parzen-window python


Phương pháp Parzen-Window (còn được gọi là Phương pháp cửa sổ Parzen-Rosenblatt) là một phương pháp không tham số được sử dụng rộng rãi để ước tính hàm mật độ xác suất P (x) cho một điểm cụ thể p (x) từ một mẫu p (xn) 'Không yêu cầu bất kỳ kiến ​​thức hoặc giả định về phân phối cơ bản.x) for a specific point p(x) from a sample p(xn) that doesn’t require any knowledge or assumption about the underlying distribution.

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Mục lục #

  • Mục lục
  • 1. Giới thiệu
  • 2 Xác định khu vực RN
    • 2.1 Hai cách tiếp cận khác nhau - Khối lượng cố định so với số mẫu cố định trong một khối lượng thay đổi
      • Trường hợp 1 - Khối lượng cố định:
      • Trường hợp 2 - Đã sửa k:
    • 2.2 Ví dụ 3D-hypercubes
    • 2.3 Hàm cửa sổ
      • 2.3.1 Thực hiện chức năng cửa sổ
      • 2.3.2 Định lượng các điểm mẫu bên trong 3D-hypercube
    • 2.4 Ước tính cửa sổ Parzen
    • 2.5 Giả định quan trọng: Sự hội tụ
    • 2.6 Các thông số quan trọng của kỹ thuật Parzen-Window: chiều rộng cửa sổ và hạt nhân
    • 2.7 Việc thực hiện ước tính cửa sổ Parzen
  • 3 Áp dụng cách tiếp cận cửa sổ Parzen cho bộ dữ liệu Gaussian đa biến ngẫu nhiên
    • 3.1 Tạo 10000 mô hình 2d ngẫu nhiên từ phân phối Gaussian
    • 3.2 Thực hiện và vẽ hàm mật độ Gaussian đa biến
      • 3.2.1 Vẽ mật độ Gaussian bivariate
      • 3.2.2 Thực hiện mã để tính toán mật độ Gaussian đa biến
        • 3.2.2.1 Kiểm tra triển khai PDF Gaussian đa biến đa biến
      • 3.2.3 So sánh ước tính cửa sổ Parzen với mật độ thực tế
        • 3.2.3.1 Chọn kích thước cửa sổ thích hợp
        • 3.2.3.2 Ước tính so với mật độ thực tế
        • 3.2.3.3 Vẽ mật độ Gaussian Bivariate ước tính
  • 4 Kết luận và nhược điểm của kỹ thuật cửa sổ Parzen
  • 5 Thay thế hypercube bằng hạt nhân Gaussian
    • 5.1 Tóm tắt việc thực hiện ước tính cửa sổ Parzen với hạt nhân HyperCube
      • 5.2 Sử dụng hạt nhân Gaussian từ
        Points inside the hypercube: 3
        Points outside the hypercube: 7
        
        6
      • 5.3 So sánh hạt nhân Gaussian và HyperCube cho chiều rộng cửa sổ tùy ý
      • 5.4 So sánh các tính toán ước tính băng thông khác nhau cho hạt nhân Gaussian
  • 6 vẽ các ước tính từ các hạt nhân khác nhau
    • 6.1 Hiệu ứng chiều rộng cửa sổ: Đỉnh địa phương và tính trung bình
  • 7 Sử dụng ước tính mật độ kernel cho một nhiệm vụ phân loại mẫu
    • Phân loại Bayes
    • 7.1 Tạo bộ dữ liệu đào tạo và kiểm tra mẫu
    • 7.2 Thực hiện trình phân loại bằng cách sử dụng quy tắc quyết định của Bayes
    • 7.3 Ước tính mật độ thông qua kỹ thuật cửa sổ Parzen với hạt nhân Gaussian
    • 7.4 Phân loại dữ liệu kiểm tra và tính toán tỷ lệ lỗi
    • Sự kết luận

1. Giới thiệu #

Phương pháp Parzen-Window (còn được gọi là Phương pháp cửa sổ Parzen-Rosenblatt) là một phương pháp không tham số được sử dụng rộng rãi để ước tính hàm mật độ xác suất P (x) cho một điểm cụ thể p (x) từ một mẫu p (xn) 'Không yêu cầu bất kỳ kiến ​​thức hoặc giả định về phân phối cơ bản.x) for a specific point p(x) from a sample p(xn) that doesn’t require any knowledge or assumption about the underlying distribution.

Đặt nó trong bối cảnh - phương pháp này sẽ hữu ích ở đâu?

Một ứng dụng phổ biến của kỹ thuật Parzen-Window là ước tính mật độ điều kiện lớp (hoặc cũng thường được gọi là 'Khả năng') P (X | I) trong một vấn đề phân loại mẫu được giám sát từ bộ dữ liệu đào tạo (trong đó p (x) đề cập đến một mẫu đa chiều thuộc lớp cụ thể ωi)).x | ωi) in a supervised pattern classification problem from the training dataset (where p(x) refers to a multi-dimensional sample that belongs to particular class ωi)).

Hãy tưởng tượng rằng chúng ta sắp thiết kế một trình phân loại Bayes để giải quyết nhiệm vụ phân loại mô hình thống kê bằng cách sử dụng quy tắc Bayes,:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Nếu các tham số của mật độ điều kiện lớp (còn được gọi là khả năng) được biết đến, thì việc thiết kế trình phân loại là khá dễ dàng. Tôi đã giải quyết một số ví dụ đơn giản trong các máy tính xách tay ipython theo các phương pháp tham số phần.


Về ký hiệu toán học:

Trong suốt bài viết này, tôi sẽ áp dụng ký hiệu ma trận phổ biến được sử dụng bởi hầu hết các sách giáo khoa đại số:

  • chữ thường có mặt in đậm bằng chữ in nghiêng (ví dụ: x) cho các vectơx) for vectors

  • chữ in in in nghiêng (ví dụ: a) cho ma trậnA) for matrices

  • các chỉ số để tham khảo các phần tử theo hàng và cột (ví dụ: \ (a_ {ij} \) cho ô trong hàng I và cột J))


Tuy nhiên, nó trở nên khó khăn hơn nhiều, nếu chúng tôi không có kiến ​​thức trước về các tham số cơ bản xác định mô hình dữ liệu của chúng tôi.

Hãy tưởng tượng chúng ta sắp thiết kế một trình phân loại cho một nhiệm vụ phân loại mẫu trong đó các tham số của phân phối mẫu cơ bản không được biết đến. Do đó, chúng tôi sẽ cần kiến ​​thức về toàn bộ phạm vi phân phối; Nó sẽ đủ để biết xác suất của điểm cụ thể, mà chúng tôi muốn phân loại, để đưa ra quyết định. Và ở đây chúng ta sẽ xem làm thế nào chúng ta có thể ước tính xác suất này từ mẫu đào tạo.

Tuy nhiên, vấn đề duy nhất của phương pháp này là chúng ta hiếm khi có các giá trị chính xác - nếu chúng ta xem xét biểu đồ của tần số cho một bộ dữ liệu đào tạo tùy ý. Do đó, chúng tôi xác định một khu vực nhất định (tức là, cửa sổ parzen) xung quanh giá trị cụ thể để đưa ra ước tính.Parzen-window) around the particular value to make the estimate.

Và cái tên này Parzen-Window đến từ đâu?

Vì nó khá phổ biến trong những ngày trước, kỹ thuật này được đặt theo tên của nhà phát minh của nó, Emanuel Parzen, người đã công bố phân tích toán học chi tiết của ông vào năm 1962 trong Biên niên sử thống kê toán học [1]. Đồng thời, một nhà thống kê thứ hai, Murray Rosenblatt [2], được phát hiện (hoặc phát triển) kỹ thuật này một cách độc lập từ Parzen để phương pháp đôi khi được gọi là phương pháp cửa sổ Parzen-Rosenblatt.


[1] Parzen, Emanuel. Về ước tính hàm và chế độ mật độ xác suất. Biên niên sử của Thống kê toán học 33 (1962), không. 3, 1065 bóng1076. doi: 10.1214/AOMS/1177704472.

[2] Rosenblatt, Murray. Nhận xét về một số ước tính không tham số của hàm mật độ. Biên niên sử của Thống kê toán học 27 (1956), không. 3, 832 bóng837. doi: 10.1214/AOMS/1177728190.

2 Xác định vùng RN #

Cơ sở của phương pháp này là đếm số lượng mẫu nằm trong một khu vực được chỉ định \ (r_ {n} \) (hoặc cửa sổ, nếu bạn muốn). Trực giác của chúng tôi cho chúng tôi biết, rằng (dựa trên quan sát), xác suất một mẫu rơi vào khu vực này là

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Để giải quyết vấn đề này từ quan điểm toán học hơn để ước tính khả năng quan sát K chỉ ra từ n trong một khu vực R, chúng tôi xem xét phân phối nhị thứcR “ we consider a binomial distribution

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

và đưa ra giả định rằng trong phân phối nhị thức, xác suất đạt cực đại ở mức trung bình, do đó:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Và nếu chúng ta nghĩ về xác suất là một biến liên tục, chúng ta biết rằng nó được định nghĩa là:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Trong đó V là khối lượng của vùng R và nếu chúng ta sắp xếp lại các thuật ngữ đó, để chúng ta đến phương trình sau, chúng ta sẽ sử dụng sau:R, and if we rearrange those terms, so that we arrive at the following equation, which we will use later:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Phương trình đơn giản này ở trên (tức là ước tính xác suất của người Viking) cho phép chúng ta tính toán mật độ xác suất của điểm X bằng cách đếm số điểm k rơi vào vùng xác định (hoặc khối lượng).x by counting how many points k fall in a defined region (or volume).

2.1 Hai cách tiếp cận khác nhau - Khối lượng cố định so với số mẫu cố định trong một khối lượng thay đổi #

Bây giờ, có hai cách tiếp cận có thể để ước tính mật độ tại các điểm khác nhau \ (p (\ mathbf {x}) \).

Trường hợp 1 - Khối lượng cố định: #

Đối với một số n cụ thể (= số tổng số điểm), chúng tôi sử dụng khối lượng V có kích thước cố định và quan sát số điểm k rơi vào khu vực. Nói cách khác, chúng tôi sử dụng cùng một khối lượng để ước tính ở các vùng khác nhau.

Kỹ thuật Parzen-Window rơi vào danh mục này!

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Trường hợp 2 - Đã sửa k: #

Đối với một số n cụ thể (= số tổng số điểm), chúng tôi sử dụng số K cố định (số điểm nằm trong khu vực hoặc âm lượng) và điều chỉnh âm lượng tương ứng. (Kỹ thuật hàng xóm gần nhất sử dụng phương pháp này, sẽ được thảo luận trong một bài viết riêng.)The k-nearest neighbor technique uses this approach, which will be discussed in a separate article.)

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

2.2 Ví dụ 3D-hypercubes #

Để minh họa điều này với một ví dụ và một tập hợp các phương trình, chúng ta hãy giả sử RN khu vực này là một hypercube. Và khối lượng của hypercube này được xác định bởi vn = hnd, trong đó HN là chiều dài của hypercube và D là số lượng kích thước. Ví dụ, đối với một-hypercube 2D có chiều dài 1, đây sẽ lần lượt là V1 = 12 và đối với HyperCube V_1 = 13 3D.
For an 2D-hypercube with length 1, for example, this would be V1 = 12 and for a 3D hypercube V_1 = 13, respectively.

Vì vậy, chúng ta hãy hình dung một ví dụ đơn giản như vậy: một hypercube đơn vị 3 chiều điển hình (H1 = 1) đại diện cho vùng R1 và 10 điểm mẫu, trong đó 3 trong số chúng nằm trong hypercube (hình tam giác màu đỏ) và 7 điểm khác bên ngoài ( Dots màu xanh).

Lưu ý rằng việc sử dụng HyperCube sẽ không phải là một lựa chọn lý tưởng cho một ứng dụng thực sự, nhưng nó chắc chắn làm cho việc triển khai các bước sau đây ngắn hơn rất nhiều và dễ theo dõi hơn..

%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure(figsize=(7,7))
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# Plot Points

# samples within the cube
X_inside = np.array([[0,0,0],[0.2,0.2,0.2],[0.1, -0.1, -0.3]])

X_outside = np.array([[-1.2,0.3,-0.3],[0.8,-0.82,-0.9],[1, 0.6, -0.7],
                  [0.8,0.7,0.2],[0.7,-0.8,-0.45],[-0.3, 0.6, 0.9],
                  [0.7,-0.6,-0.8]])

for row in X_inside:
    ax.scatter(row[0], row[1], row[2], color="r", s=50, marker='^')

for row in X_outside:
    ax.scatter(row[0], row[1], row[2], color="k", s=50)

# Plot Cube
h = [-0.5, 0.5]
for s, e in combinations(np.array(list(product(h,h,h))), 2):
    if np.sum(np.abs(s-e)) == h[1]-h[0]:
        ax.plot3D(*zip(s,e), color="g")

ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)

plt.show()

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

2.3 Hàm cửa sổ #

Một khi chúng tôi hình dung khu vực R1 như trên, thật dễ dàng và trực quan khi đếm số lượng mẫu nằm trong khu vực này và bao nhiêu nằm bên ngoài. Để tiếp cận vấn đề này về mặt toán học hơn, chúng tôi sẽ sử dụng phương trình sau để đếm các mẫu kN trong hypercube này, trong đó φ là chức năng được gọi là cửa sổ của chúng tôiR1 like above, it is easy and intuitive to count how many samples fall within this region, and how many lie outside. To approach this problem more mathematically, we would use the following equation to count the samples kn within this hypercube, where φ is our so-called window function

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Đối với một hypercube có chiều dài đơn vị 1 tập trung vào nguồn gốc của hệ tọa độ.

Những gì chức năng này về cơ bản là gán một giá trị 1 cho một điểm mẫu nếu nó nằm trong phạm vi 1/2 của các cạnh của hypercube và 0 nếu nằm bên ngoài (lưu ý rằng việc đánh giá được thực hiện cho tất cả các kích thước của điểm mẫu).

Nếu chúng ta mở rộng cho khái niệm này, chúng ta có thể xác định một phương trình tổng quát hơn áp dụng cho các hypercub của bất kỳ HN có độ dài nào được tập trung tại X:x:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

2.3.1 Thực hiện chức năng cửa sổ #

def window_function(x_vec, unit_len=1):
"""
Implementation of the window function. Returns 1 if 3x1-sample vector
lies within a origin-centered hypercube, 0 otherwise.

"""
for row in x_vec:
    if np.abs(row) > (unit_len/2):
        return 0
return 1

2.3.2 Định lượng các điểm mẫu bên trong 3D-hypercube #

Sử dụng chức năng cửa sổ mà chúng tôi vừa triển khai ở trên, bây giờ chúng ta hãy định lượng có bao nhiêu điểm thực sự nằm bên trong và bên ngoài HyperCube.

X_all = np.vstack((X_inside,X_outside))
assert(X_all.shape == (10,3))

k_n = 0
for row in X_all:
    k_n += window_function(row.reshape(3,1))

print('Points inside the hypercube:', k_n)
print('Points outside the hybercube:', len(X_all) - k_n)

Points inside the hypercube: 3
Points outside the hypercube: 7

Dựa trên chức năng cửa sổ mà chúng tôi xác định trong phần trên, giờ đây chúng tôi có thể xây dựng ước tính Parzen-Window với hạt nhân HyperCube như sau:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Và áp dụng điều này vào ví dụ đơn vị-hypercube của chúng tôi ở trên, trong đó 3 trong số 10 mẫu nằm trong hypercube (vào vùng R), chúng tôi có thể tính toán xác suất P (x) mà các mẫu X nằm trong vùng R như sau:x) that x samples fall within region R as follows:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

2.5 Giả định quan trọng: Hội tụ #

Một trong những giả định quan trọng nhất tại sao kỹ thuật Parzen-Window hoạt động (cũng như kỹ thuật hàng xóm gần nhất K) là PN (trong đó chỉ số N biểu thị số lượng mẫu của các mẫu Chúng tôi cho rằng một số lượng vô hạn các mẫu đào tạo, được Emanuel Parzen thể hiện độc đáo trong bài báo của mình.x) when we assume an infinite number of training samples, which was nicely shown by Emanuel Parzen in his paper.

2.6 Các thông số quan trọng của kỹ thuật Parzen-Window: chiều rộng cửa sổ và kernel #

Hai tham số quan trọng trong các kỹ thuật cửa sổ parzen là

  • 1) Chiều rộng cửa sổ
  • 2) Hạt nhân

1) Chiều rộng cửa sổ: Hãy để chúng tôi bỏ qua phần này ngay bây giờ và thảo luận và khám phá câu hỏi về việc chọn một chiều rộng cửa sổ thích hợp sau đó bằng cách sử dụng một ví dụ thực hành.
Let us skip this part for now and discuss and explore the question of choosing an appropriate window width later by using an hands-on example.

2) Kernel: Thông thường nhất, một hypercube hoặc hạt nhân Gaussian được sử dụng cho chức năng cửa sổ. Nhưng làm thế nào để chúng ta biết cái nào tốt hơn? Nó thực sự phụ thuộc vào mẫu đào tạo. Trong thực tế, sự lựa chọn thường được thực hiện bằng cách kiểm tra trình phân loại mẫu dẫn xuất để xem phương pháp nào dẫn đến hiệu suất tốt hơn trên tập dữ liệu thử nghiệm. Theo trực giác, sẽ có ý nghĩa khi sử dụng một hạt nhân Gaussian cho một bộ dữ liệu theo phân phối Gaussian. Nhưng hãy nhớ rằng, toàn bộ mục đích của ước tính Parzen-Window là ước tính mật độ của một phân phối không xác định! Vì vậy, trong thực tế, chúng tôi sẽ biết liệu dữ liệu của chúng tôi có bắt nguồn từ phân phối Gaussian hay không (nếu không chúng tôi sẽ cần ước tính, nhưng có thể sử dụng một kỹ thuật tham số như ước tính MLE hoặc Bayes). Nếu chúng ta quyết định sử dụng hạt nhân Gaussian thay vì hypercube, chúng ta chỉ có thể đổi các điều khoản của hàm cửa sổ, mà chúng ta đã xác định ở trên cho HyperCube, bằng cách:::
Most commonly, either a hypercube or a Gaussian kernel is used for the window function. But how do we know which is better? It really depends on the training sample. In practice, the choice is often made by testing the derived pattern classifier to see which method leads to a better performance on the test data set.
Intuitively, it would make sense to use a Gaussian kernel for a data set that follows a Gaussian distribution. But remember, the whole purpose of the Parzen-window estimation is to estimate densities of a unknown distribution! So, in practice we wouldn’t know whether our data stems from a Gaussian distribution or not (otherwise we wouldn’t need to estimate, but can use a parametric technique like MLE or Bayesian Estimation).
If we would decide to use a Gaussian kernel instead of the hypercube, we can just simply swap the terms of the window function, which we defined above for the hypercube, by:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Ước tính Parzen-Window sau đó sẽ trông như thế này:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Trộn các hạt nhân khác nhau: Trong một số bài báo bạn sẽ thấy, các tác giả trộn hạt nhân HyperCube và Gaussian để ước tính mật độ ở các vùng khác nhau. Trong thực tế, điều này có thể hoạt động rất tốt, tuy nhiên, lưu ý rằng về lý thuyết, điều này sẽ vi phạm các nguyên tắc cơ bản: mật độ tích hợp vào 1.
In some papers you will see, that the authors mixed hypercube and Gaussian kernels to estimate the densities at different regions. In practice, this might work very well, however, but note that in theory this would violate on of the underlying principles: that the density integrates to 1.

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

  • Một vài yêu cầu khác là ở giới hạn khối lượng chúng tôi chọn cho cửa sổ Parzen trở nên vô hạn nhỏ.

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

  • Số lượng điểm KN trong khu vực này hội tụ đến:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

  • từ đó chúng ta có thể kết luận:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

2.7 Thực hiện ước tính Parzen-Window #

Và một lần nữa, chúng ta hãy đi đến phần thú vị hơn và triển khai mã cho kernel HyperCube:

def parzen_window_est(x_samples, h=1, center=[0,0,0]):
    '''
    Implementation of the Parzen-window estimation for hypercubes.

    Keyword arguments:
        x_samples: A 'n x d'-dimensional numpy array, where each sample
            is stored in a separate row.
        h: The length of the hypercube.
        center: The coordinate center of the hypercube

    Returns the probability density for observing k samples inside the hypercube.

    '''
    dimensions = x_samples.shape[1]

    assert (len(center) == dimensions),  
            'Number of center coordinates have to match sample dimensions'
    k = 0
    for x in x_samples:
        is_inside = 1
        for axis,center_point in zip(x, center):
            if np.abs(axis-center_point) > (h/2):
                is_inside = 0
        k += is_inside
    return (k / len(x_samples)) / (h**dimensions)

print('p(x) =', parzen_window_est(X_all, h=1))

Tại thời điểm này, tôi hoàn toàn có thể hiểu nếu bạn mất tổng quan một chút. Tôi đã tóm tắt ba phần quan trọng (kernel hypercube, chức năng cửa sổ và ước tính parzen-window kết quả) trong phần sau và tôi nghĩ rằng nó đáng để xem xét ngắn gọn về nó, trước khi chúng tôi áp dụng nó vào một tập dữ liệu bên dưới.

3 Áp dụng phương pháp parzen-Window cho bộ dữ liệu Gaussian đa biến ngẫu nhiên #

Chúng ta hãy sử dụng bộ dữ liệu 2 chiều được rút ra từ phân phối Gaussian đa biến để áp dụng kỹ thuật Parzen-Window để ước tính mật độ.

3.1 Tạo 10000 mẫu 2D ngẫu nhiên từ phân phối Gaussian #

Hàm mật độ xác suất Gaussian đa biến chung (PDF) được định nghĩa là:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Và chúng tôi sẽ sử dụng các tham số sau để vẽ các mẫu ngẫu nhiên:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

import numpy as np

# Generate 10,000 random 2D-patterns
mu_vec = np.array([0,0])
cov_mat = np.array([[1,0],[0,1]])
x_2Dgauss = np.random.multivariate_normal(mu_vec, cov_mat, 10000)

print(x_2Dgauss.shape)

#from matplotlib import pyplot as plt

f, ax = plt.subplots(figsize=(7, 7))
ax.scatter(x_2Dgauss[:,0], x_2Dgauss[:,1],
        marker='o', color='green', s=4, alpha=0.3)
plt.title('10000 samples randomly drawn from a 2D Gaussian distribution')
plt.ylabel('x2')
plt.xlabel('x1')
ftext = 'p(x) ~ N(mu=(0,0)^t, cov=I)'
plt.figtext(.15,.85, ftext, fontsize=11, ha='left')
plt.ylim([-4,4])
plt.xlim([-4,4])

plt.show()

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

3.2 Thực hiện và vẽ hàm mật độ Gaussian đa biến #

3.2.1 Vẽ mật độ Gaussian bivariate #

Đầu tiên, chúng ta hãy vẽ sơ đồ phân phối Gaussian đa biến (ở đây: bivariate) trong một ô 3D để có ý tưởng tốt hơn về phân phối mật độ thực tế.

#import numpy as np
#from matplotlib import pyplot as plt

from matplotlib.mlab import bivariate_normal
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(10, 7))
ax = fig.gca(projection='3d')
x = np.linspace(-5, 5, 200)
y = x
X,Y = np.meshgrid(x, y)
Z = bivariate_normal(X, Y)
surf = ax.plot_surface(X, Y, Z, rstride=1,
        cstride=1, cmap=plt.cm.coolwarm,
        linewidth=0, antialiased=False
    )

ax.set_zlim(0, 0.2)
ax.zaxis.set_major_locator(plt.LinearLocator(10))
ax.zaxis.set_major_formatter(plt.FormatStrFormatter('%.02f'))

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('p(x)')

plt.title('Bivariate Gaussian distribution')
fig.colorbar(surf, shrink=0.5, aspect=7, cmap=plt.cm.coolwarm)

plt.show()

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

3.2.2 Thực hiện mã để tính mật độ Gaussian đa biến #

Để tính toán xác suất từ ​​hàm mật độ Gaussian đa biến và so sánh kết quả ước tính của chúng tôi, hãy để chúng tôi thực hiện nó bằng phương trình sau:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Thật không may, hiện tại không có thư viện Python cung cấp chức năng này. Tin tốt là,

Points inside the hypercube: 3
Points outside the hypercube: 7
7 sẽ được triển khai trong ứng cử viên phát hành mới là
Points inside the hypercube: 3
Points outside the hypercube: 7
8 (câu 0,14).

#import numpy as np

def pdf_multivariate_gauss(x, mu, cov):
    '''
    Caculate the multivariate normal density (pdf)

    Keyword arguments:
        x = numpy array of a "d x 1" sample vector
        mu = numpy array of a "d x 1" mean vector
        cov = "numpy array of a d x d" covariance matrix
    '''
    assert(mu.shape[0] > mu.shape[1]),\
        'mu must be a row vector'
    assert(x.shape[0] > x.shape[1]),\
        'x must be a row vector'
    assert(cov.shape[0] == cov.shape[1]),\
        'covariance matrix must be square'
    assert(mu.shape[0] == cov.shape[0]),\
        'cov_mat and mu_vec must have the same dimensions'
    assert(mu.shape[0] == x.shape[0]),\
        'mu and x must have the same dimensions'

    part1 = 1 / ( ((2* np.pi)**(len(mu)/2)) * (np.linalg.det(cov)**(1/2)) )
    part2 = (-1/2) * ((x-mu).T.dot(np.linalg.inv(cov))).dot((x-mu))
    return float(part1 * np.exp(part2))

3.2.2.1 Kiểm tra triển khai PDF Gaussian đa biến #

Chúng ta hãy nhanh chóng xác nhận rằng Gaussian đa biến, mà chúng tôi vừa triển khai, hoạt động như mong đợi bằng cách so sánh nó với Gaussian bivariate từ gói matplotlib.mlab.

%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure(figsize=(7,7))
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# Plot Points

# samples within the cube
X_inside = np.array([[0,0,0],[0.2,0.2,0.2],[0.1, -0.1, -0.3]])

X_outside = np.array([[-1.2,0.3,-0.3],[0.8,-0.82,-0.9],[1, 0.6, -0.7],
                  [0.8,0.7,0.2],[0.7,-0.8,-0.45],[-0.3, 0.6, 0.9],
                  [0.7,-0.6,-0.8]])

for row in X_inside:
    ax.scatter(row[0], row[1], row[2], color="r", s=50, marker='^')

for row in X_outside:
    ax.scatter(row[0], row[1], row[2], color="k", s=50)

# Plot Cube
h = [-0.5, 0.5]
for s, e in combinations(np.array(list(product(h,h,h))), 2):
    if np.sum(np.abs(s-e)) == h[1]-h[0]:
        ax.plot3D(*zip(s,e), color="g")

ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)

plt.show()
0

%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure(figsize=(7,7))
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# Plot Points

# samples within the cube
X_inside = np.array([[0,0,0],[0.2,0.2,0.2],[0.1, -0.1, -0.3]])

X_outside = np.array([[-1.2,0.3,-0.3],[0.8,-0.82,-0.9],[1, 0.6, -0.7],
                  [0.8,0.7,0.2],[0.7,-0.8,-0.45],[-0.3, 0.6, 0.9],
                  [0.7,-0.6,-0.8]])

for row in X_inside:
    ax.scatter(row[0], row[1], row[2], color="r", s=50, marker='^')

for row in X_outside:
    ax.scatter(row[0], row[1], row[2], color="k", s=50)

# Plot Cube
h = [-0.5, 0.5]
for s, e in combinations(np.array(list(product(h,h,h))), 2):
    if np.sum(np.abs(s-e)) == h[1]-h[0]:
        ax.plot3D(*zip(s,e), color="g")

ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)

plt.show()
1

3.2.3 So sánh ước tính cửa sổ Parzen với mật độ thực tế #

Và cuối cùng, chúng ta hãy so sánh các mật độ mà chúng ta ước tính sử dụng việc thực hiện ước tính Parzen-Window với mật độ Gaussian đa biến thực tế.

Nhưng trước khi chúng tôi thực hiện so sánh, chúng tôi phải tự hỏi mình thêm một câu hỏi: chúng tôi nên chọn kích thước cửa sổ nào (tức là, giá trị h bên h của hypercube của chúng tôi) là gì? Chiều rộng cửa sổ là một hàm của số lượng mẫu đào tạo,

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Nhưng tại sao √n, không chỉ n?

Điều này là do số lượng điểm KN trong cửa sổ tăng nhỏ hơn nhiều so với số lượng mẫu đào tạo, mặc dù

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Chúng tôi có: k

Đây cũng là một trong những nhược điểm lớn nhất của kỹ thuật Parzen-Window, vì trong thực tế, số lượng dữ liệu đào tạo thường (quá) nhỏ, khiến cho việc lựa chọn kích thước cửa sổ tối ưu.

Trong thực tế, người ta sẽ chọn các chiều rộng cửa sổ khác nhau và phân tích kết quả nào trong hiệu suất tốt nhất của trình phân loại dẫn xuất. Hướng dẫn duy nhất chúng tôi có là chúng tôi cho rằng ‘tối ưu chiều rộng cửa sổ co lại với số lượng mẫu đào tạo. The only guideline we have is that we assume that ‘optimal’ the window width shrinks with the number of training samples.

Nếu chúng ta chọn một chiều rộng cửa sổ là quá nhỏ, thì điều này sẽ dẫn đến các đột biến cục bộ và chiều rộng cửa sổ là quá lớn sẽ trung bình trong toàn bộ phân phối. Dưới đây, tôi cố gắng minh họa nó bằng cách sử dụng mẫu 1D.

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Trong phần sau, chúng tôi sẽ xem xét nó trông như thế nào trong trường hợp dữ liệu ví dụ của chúng tôi:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

3.2.3.1 Chọn kích thước cửa sổ thích hợp #

Ví dụ của chúng tôi, chúng tôi có sự xa xỉ khi biết phân phối dữ liệu của chúng tôi, vì vậy chúng tôi hãy xem xét một số chiều rộng cửa sổ có thể để xem nó ảnh hưởng đến việc ước tính mật độ cho trung tâm phân phối như thế nào (dựa trên thử nghiệm của chúng tôi trong phần trên, chúng tôi sẽ mong đợi một giá trị gần với p (x) = 0.1592).
(based on our test in the section above, we would expect a value close to p(x) = 0.1592 ).

%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure(figsize=(7,7))
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# Plot Points

# samples within the cube
X_inside = np.array([[0,0,0],[0.2,0.2,0.2],[0.1, -0.1, -0.3]])

X_outside = np.array([[-1.2,0.3,-0.3],[0.8,-0.82,-0.9],[1, 0.6, -0.7],
                  [0.8,0.7,0.2],[0.7,-0.8,-0.45],[-0.3, 0.6, 0.9],
                  [0.7,-0.6,-0.8]])

for row in X_inside:
    ax.scatter(row[0], row[1], row[2], color="r", s=50, marker='^')

for row in X_outside:
    ax.scatter(row[0], row[1], row[2], color="k", s=50)

# Plot Cube
h = [-0.5, 0.5]
for s, e in combinations(np.array(list(product(h,h,h))), 2):
    if np.sum(np.abs(s-e)) == h[1]-h[0]:
        ax.plot3D(*zip(s,e), color="g")

ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)

plt.show()
2

%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure(figsize=(7,7))
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# Plot Points

# samples within the cube
X_inside = np.array([[0,0,0],[0.2,0.2,0.2],[0.1, -0.1, -0.3]])

X_outside = np.array([[-1.2,0.3,-0.3],[0.8,-0.82,-0.9],[1, 0.6, -0.7],
                  [0.8,0.7,0.2],[0.7,-0.8,-0.45],[-0.3, 0.6, 0.9],
                  [0.7,-0.6,-0.8]])

for row in X_inside:
    ax.scatter(row[0], row[1], row[2], color="r", s=50, marker='^')

for row in X_outside:
    ax.scatter(row[0], row[1], row[2], color="k", s=50)

# Plot Cube
h = [-0.5, 0.5]
for s, e in combinations(np.array(list(product(h,h,h))), 2):
    if np.sum(np.abs(s-e)) == h[1]-h[0]:
        ax.plot3D(*zip(s,e), color="g")

ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)

plt.show()
3

Ước tính sơ bộ này ở trên cho chúng ta một số ý tưởng về kích thước cửa sổ sẽ cho chúng ta ước tính khá hợp lý: một giá trị tốt cho \ (h \) nên ở đâu đó khoảng 0,6.

Nhưng chúng ta có thể làm tốt hơn (có lẽ tôi nên sử dụng một thuật toán giảm thiểu ở đây, nhưng tôi nghĩ ví dụ này sẽ minh họa đủ quy trình). Vì vậy, chúng ta hãy tạo 400 giá trị cách đều nhau giữa (0,1) cho H và xem điều này cho chúng ta ước tính xác suất ở trung tâm của phân phối.

%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure(figsize=(7,7))
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# Plot Points

# samples within the cube
X_inside = np.array([[0,0,0],[0.2,0.2,0.2],[0.1, -0.1, -0.3]])

X_outside = np.array([[-1.2,0.3,-0.3],[0.8,-0.82,-0.9],[1, 0.6, -0.7],
                  [0.8,0.7,0.2],[0.7,-0.8,-0.45],[-0.3, 0.6, 0.9],
                  [0.7,-0.6,-0.8]])

for row in X_inside:
    ax.scatter(row[0], row[1], row[2], color="r", s=50, marker='^')

for row in X_outside:
    ax.scatter(row[0], row[1], row[2], color="k", s=50)

# Plot Cube
h = [-0.5, 0.5]
for s, e in combinations(np.array(list(product(h,h,h))), 2):
    if np.sum(np.abs(s-e)) == h[1]-h[0]:
        ax.plot3D(*zip(s,e), color="g")

ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)

plt.show()
4

%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure(figsize=(7,7))
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# Plot Points

# samples within the cube
X_inside = np.array([[0,0,0],[0.2,0.2,0.2],[0.1, -0.1, -0.3]])

X_outside = np.array([[-1.2,0.3,-0.3],[0.8,-0.82,-0.9],[1, 0.6, -0.7],
                  [0.8,0.7,0.2],[0.7,-0.8,-0.45],[-0.3, 0.6, 0.9],
                  [0.7,-0.6,-0.8]])

for row in X_inside:
    ax.scatter(row[0], row[1], row[2], color="r", s=50, marker='^')

for row in X_outside:
    ax.scatter(row[0], row[1], row[2], color="k", s=50)

# Plot Cube
h = [-0.5, 0.5]
for s, e in combinations(np.array(list(product(h,h,h))), 2):
    if np.sum(np.abs(s-e)) == h[1]-h[0]:
        ax.plot3D(*zip(s,e), color="g")

ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)

plt.show()
5

3.2.3.2 Ước tính so với mật độ thực tế #

Bây giờ, rằng chúng ta có một chiều rộng cửa sổ phù hợp của người Viking, chúng ta hãy so sánh các ước tính với mật độ thực tế cho một số điểm ví dụ.

%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure(figsize=(7,7))
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# Plot Points

# samples within the cube
X_inside = np.array([[0,0,0],[0.2,0.2,0.2],[0.1, -0.1, -0.3]])

X_outside = np.array([[-1.2,0.3,-0.3],[0.8,-0.82,-0.9],[1, 0.6, -0.7],
                  [0.8,0.7,0.2],[0.7,-0.8,-0.45],[-0.3, 0.6, 0.9],
                  [0.7,-0.6,-0.8]])

for row in X_inside:
    ax.scatter(row[0], row[1], row[2], color="r", s=50, marker='^')

for row in X_outside:
    ax.scatter(row[0], row[1], row[2], color="k", s=50)

# Plot Cube
h = [-0.5, 0.5]
for s, e in combinations(np.array(list(product(h,h,h))), 2):
    if np.sum(np.abs(s-e)) == h[1]-h[0]:
        ax.plot3D(*zip(s,e), color="g")

ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)

plt.show()
6

%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure(figsize=(7,7))
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# Plot Points

# samples within the cube
X_inside = np.array([[0,0,0],[0.2,0.2,0.2],[0.1, -0.1, -0.3]])

X_outside = np.array([[-1.2,0.3,-0.3],[0.8,-0.82,-0.9],[1, 0.6, -0.7],
                  [0.8,0.7,0.2],[0.7,-0.8,-0.45],[-0.3, 0.6, 0.9],
                  [0.7,-0.6,-0.8]])

for row in X_inside:
    ax.scatter(row[0], row[1], row[2], color="r", s=50, marker='^')

for row in X_outside:
    ax.scatter(row[0], row[1], row[2], color="k", s=50)

# Plot Cube
h = [-0.5, 0.5]
for s, e in combinations(np.array(list(product(h,h,h))), 2):
    if np.sum(np.abs(s-e)) == h[1]-h[0]:
        ax.plot3D(*zip(s,e), color="g")

ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)

plt.show()
7

Như chúng ta có thể thấy trong bảng trên, dự đoán của chúng tôi hoạt động khá tốt!

3.2.3.3 Vẽ mật độ Gaussian Bivariate ước tính #

Cuối cùng nhưng không kém phần quan trọng, chúng ta hãy vẽ các mật độ mà chúng ta dự đoán bằng cách sử dụng kỹ thuật Parzen-Window với HyperCube.

%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure(figsize=(7,7))
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# Plot Points

# samples within the cube
X_inside = np.array([[0,0,0],[0.2,0.2,0.2],[0.1, -0.1, -0.3]])

X_outside = np.array([[-1.2,0.3,-0.3],[0.8,-0.82,-0.9],[1, 0.6, -0.7],
                  [0.8,0.7,0.2],[0.7,-0.8,-0.45],[-0.3, 0.6, 0.9],
                  [0.7,-0.6,-0.8]])

for row in X_inside:
    ax.scatter(row[0], row[1], row[2], color="r", s=50, marker='^')

for row in X_outside:
    ax.scatter(row[0], row[1], row[2], color="k", s=50)

# Plot Cube
h = [-0.5, 0.5]
for s, e in combinations(np.array(list(product(h,h,h))), 2):
    if np.sum(np.abs(s-e)) == h[1]-h[0]:
        ax.plot3D(*zip(s,e), color="g")

ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)

plt.show()
8

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

4 Kết luận và nhược điểm của kỹ thuật Parzen-Window #

Như chúng ta thấy trong hai hình trên (ước tính so với phân phối xác suất Gaussian thực tế so với Bivariate), chúng tôi có thể ước tính mật độ Gaussian hợp lý.

Tính toán và hiệu suất

Một trong những nhược điểm lớn nhất của kỹ thuật Parzen-Window là chúng tôi phải giữ bộ dữ liệu đào tạo của mình xung quanh để ước tính (tính toán) mật độ xác suất. Ví dụ: nếu chúng ta thiết kế một bộ phân loại Bayes và sử dụng kỹ thuật Parzen-Window để ước tính mật độ xác suất điều kiện của lớp P (XI |keep our training dataset around for estimating (computing) the probability densities. For example, if we design a Bayes’ classifier and use the Parzen-window technique to estimate the class-conditional probability densities p(xi | ωj), the computational task requires the whole training dataset to make the estimate for every point

  • Đây là một nhược điểm của các phương pháp không tham số nói chung. Ngược lại, các phương pháp tham số, ví dụ, ước tính khả năng tối đa (MLE) hoặc ước tính Bayesian (BE) chỉ yêu cầu dữ liệu đào tạo để tính giá trị của các tham số. Khi, các tham số được lấy từ bộ dữ liệu đào tạo, nó có thể bị loại bỏ và không cần phải tính toán lại để phân loại dữ liệu trong bộ dữ liệu thử nghiệm. Tuy nhiên, trong học tập Bayes (BL), các mẫu mới có thể được kết hợp để cải thiện các giá trị tham số ước tính.
    In contrast, parametric methods, e.g., the Maximum Likelihood Estimate (MLE) or Bayesian Estimation (BE) only require the training data to calculate the value of the parameters. Once, the parameters were obtained from the training dataset, it can be discarded and re-computation is not required for classifying data in the test dataset. However, in Bayesian Learning (BL), new samples can be incorporated to improve the estimated parameter values.

Kích thước của bộ dữ liệu đào tạo

Vì kỹ thuật Parzen-Window ước tính mật độ xác suất dựa trên bộ dữ liệu đào tạo, nó cũng phụ thuộc vào kích thước hợp lý của các mẫu đào tạo để đưa ra ước tính tốt. Các mẫu đào tạo chúng ta có nhiều hơn trong bộ dữ liệu đào tạo, gần như nói, ước tính càng chính xác (định lý giới hạn trung tâm) vì chúng ta giảm khả năng gặp phải sự thưa thớt các điểm cho các khu vực địa phương - giả sử rằng các mẫu đào tạo của chúng ta là I.I.D được vẽ và phân phối giống hệt nhau). Tuy nhiên, mặt khác, một số lượng lớn hơn hoặc các mẫu đào tạo cũng sẽ dẫn đến giảm hiệu suất tính toán như được thảo luận trong phần trên.independently drawn and identically distributed). However, on the other hand, a larger number or training samples will also lead to a decrease of the computational performance as discussed in the section above.

Chọn chiều rộng cửa sổ thích hợp

Chọn một chiều rộng cửa sổ thích hợp là một nhiệm vụ rất khó khăn, vì chúng tôi không có kiến ​​thức về việc phân phối dữ liệu đào tạo (nếu không thì phương pháp không tham số sẽ bị lỗi thời) và do đó chúng tôi phải đánh giá chiều rộng cửa sổ khác nhau bằng cách phân tích hiệu suất của Trình phân loại có nguồn gốc trong một nhiệm vụ phân loại mẫu, sử dụng giả định

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

như một hướng dẫn.

Chọn hạt nhân

Thông thường nhất, một hạt nhân HyperCube hoặc Gaussian được chọn cho chức năng cửa sổ Parzen. Tuy nhiên, không thể biết hạt nhân nào sẽ mang lại ước tính tốt hơn về mật độ xác suất trước đó, vì chúng tôi cho rằng chúng tôi không có kiến ​​thức nào về phân phối cơ bản khi chúng tôi đang sử dụng kỹ thuật cửa sổ Parzen. Tương tự như chọn một chiều rộng cửa sổ thích hợp, chúng tôi cũng phải đánh giá hiệu suất của trình phân loại dẫn xuất để đưa ra lựa chọn thực tế.

5 Thay thế HyperCube bằng hạt nhân Gaussian #

Làm việc thông qua các ví dụ ở trên, chúng tôi ước tính mật độ xác suất cho phân phối Gaussian bivariate sử dụng hạt nhân HyperCube và ước tính cửa sổ Parzen của chúng tôi đã được thực hiện bằng phương trình sau:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Bây giờ, chúng ta hãy chuyển sang kernel Gaussian cho ước tính cửa sổ Parzen, để phương trình trở thành:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

ở đâu

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Và áp dụng điều này để ra khỏi đơn vị-hypercube ở trên, trong đó 3 trong số 10 mẫu nằm trong hypercube (vùng R), chúng ta có thể tính toán xác suất P (x) mà các mẫu X nằm trong vùng R như sau:x) that x samples fall within region R as follows:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

5.1 Tóm tắt việc thực hiện ước tính cửa sổ Parzen với hạt nhân HyperCube #

Chúng ta hãy nhanh chóng tóm tắt cách chúng tôi thực hiện ước tính Parzen-Window cho HyperCube.

%matplotlib inline

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure(figsize=(7,7))
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# Plot Points

# samples within the cube
X_inside = np.array([[0,0,0],[0.2,0.2,0.2],[0.1, -0.1, -0.3]])

X_outside = np.array([[-1.2,0.3,-0.3],[0.8,-0.82,-0.9],[1, 0.6, -0.7],
                  [0.8,0.7,0.2],[0.7,-0.8,-0.45],[-0.3, 0.6, 0.9],
                  [0.7,-0.6,-0.8]])

for row in X_inside:
    ax.scatter(row[0], row[1], row[2], color="r", s=50, marker='^')

for row in X_outside:
    ax.scatter(row[0], row[1], row[2], color="k", s=50)

# Plot Cube
h = [-0.5, 0.5]
for s, e in combinations(np.array(list(product(h,h,h))), 2):
    if np.sum(np.abs(s-e)) == h[1]-h[0]:
        ax.plot3D(*zip(s,e), color="g")

ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)

plt.show()
9

Hãy để Lừa quay trở lại ví dụ HyperCube trong đó 3 điểm nằm bên trong, 7 điểm nằm ngoài HyperCube và ước tính mật độ của chúng tôi đối với HyperCube đơn vị-1 ở trung tâm là P (x) = 0,3.x) = 0.3.

def window_function(x_vec, unit_len=1):
"""
Implementation of the window function. Returns 1 if 3x1-sample vector
lies within a origin-centered hypercube, 0 otherwise.

"""
for row in x_vec:
    if np.abs(row) > (unit_len/2):
        return 0
return 1
0

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Bây giờ chúng ta có thể sử dụng chức năng

Points inside the hypercube: 3
Points outside the hypercube: 7
9 với hạt nhân HyperCube để tính P (x).x).

def window_function(x_vec, unit_len=1):
"""
Implementation of the window function. Returns 1 if 3x1-sample vector
lies within a origin-centered hypercube, 0 otherwise.

"""
for row in x_vec:
    if np.abs(row) > (unit_len/2):
        return 0
return 1
1

Và chúng ta hãy nhanh chóng xác nhận rằng nó hoạt động trên một bộ dữ liệu lớn hơn cho các siêu đơn vị không được tập trung ở nguồn gốc: (Lưu ý rằng tôi chỉ chọn độ dài tùy ý cho H, đây có thể không phải là lựa chọn tốt nhất cho H.)
(Note that I just chose an arbitrary length for h, this is likely not the best choice for h.)

def window_function(x_vec, unit_len=1):
"""
Implementation of the window function. Returns 1 if 3x1-sample vector
lies within a origin-centered hypercube, 0 otherwise.

"""
for row in x_vec:
    if np.abs(row) > (unit_len/2):
        return 0
return 1
2

def window_function(x_vec, unit_len=1):
"""
Implementation of the window function. Returns 1 if 3x1-sample vector
lies within a origin-centered hypercube, 0 otherwise.

"""
for row in x_vec:
    if np.abs(row) > (unit_len/2):
        return 0
return 1
3

def window_function(x_vec, unit_len=1):
"""
Implementation of the window function. Returns 1 if 3x1-sample vector
lies within a origin-centered hypercube, 0 otherwise.

"""
for row in x_vec:
    if np.abs(row) > (unit_len/2):
        return 0
return 1
4

5.2 Sử dụng hạt nhân Gaussian từ Points inside the hypercube: 3 Points outside the hypercube: 7 6 #

Vì chúng tôi đã trải qua kỹ thuật Parzen-Window từng bước cho hạt nhân HyperCube, chúng tôi hãy nhập lớp

def parzen_window_est(x_samples, h=1, center=[0,0,0]):
    '''
    Implementation of the Parzen-window estimation for hypercubes.

    Keyword arguments:
        x_samples: A 'n x d'-dimensional numpy array, where each sample
            is stored in a separate row.
        h: The length of the hypercube.
        center: The coordinate center of the hypercube

    Returns the probability density for observing k samples inside the hypercube.

    '''
    dimensions = x_samples.shape[1]

    assert (len(center) == dimensions),  
            'Number of center coordinates have to match sample dimensions'
    k = 0
    for x in x_samples:
        is_inside = 1
        for axis,center_point in zip(x, center):
            if np.abs(axis-center_point) > (h/2):
                is_inside = 0
        k += is_inside
    return (k / len(x_samples)) / (h**dimensions)

print('p(x) =', parzen_window_est(X_all, h=1))
1 từ gói
Points inside the hypercube: 3
Points outside the hypercube: 7
8 để tiếp cận thuận tiện hơn.

Tài liệu hoàn chỉnh có thể được tìm thấy trên Docs.Scipy.org.

Lớp

def parzen_window_est(x_samples, h=1, center=[0,0,0]):
    '''
    Implementation of the Parzen-window estimation for hypercubes.

    Keyword arguments:
        x_samples: A 'n x d'-dimensional numpy array, where each sample
            is stored in a separate row.
        h: The length of the hypercube.
        center: The coordinate center of the hypercube

    Returns the probability density for observing k samples inside the hypercube.

    '''
    dimensions = x_samples.shape[1]

    assert (len(center) == dimensions),  
            'Number of center coordinates have to match sample dimensions'
    k = 0
    for x in x_samples:
        is_inside = 1
        for axis,center_point in zip(x, center):
            if np.abs(axis-center_point) > (h/2):
                is_inside = 0
        k += is_inside
    return (k / len(x_samples)) / (h**dimensions)

print('p(x) =', parzen_window_est(X_all, h=1))
1 lấy 2 tham số làm đầu vào

  • DataSet:

    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    4 Datapoints để ước tính từ. Trong trường hợp dữ liệu đơn biến, đây là mảng 1-D, nếu không thì một mảng 2 chiều có hình ( # của DIMS, # của dữ liệu). :
    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    4 Datapoints to estimate from. In case of univariate data this is a 1-D array, otherwise a 2-D array with shape (# of dims, # of data).

  • BW_METHOD:

    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    5 Phương pháp được sử dụng để tính toán băng thông ước tính. Đây có thể là
    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    6,
    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    7, hằng số vô hướng hoặc có thể gọi được. Nếu một vô hướng, điều này sẽ được sử dụng trực tiếp làm kde.factor. Nếu có thể gọi được, nó sẽ lấy một thể hiện Gaussian_kde là tham số chỉ và trả về vô hướng. Nếu
    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    8 (mặc định),
    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    6 được sử dụng. Xem ghi chú để biết thêm chi tiết.
    :
    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    5 The method used to calculate the estimator bandwidth. This can be
    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    6,
    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    7, a scalar constant or a callable. If a scalar, this will be used directly as kde.factor. If a callable, it should take a gaussian_kde instance as only parameter and return a scalar. If
    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    8 (default),
    def parzen_window_est(x_samples, h=1, center=[0,0,0]):
        '''
        Implementation of the Parzen-window estimation for hypercubes.
    
        Keyword arguments:
            x_samples: A 'n x d'-dimensional numpy array, where each sample
                is stored in a separate row.
            h: The length of the hypercube.
            center: The coordinate center of the hypercube
    
        Returns the probability density for observing k samples inside the hypercube.
    
        '''
        dimensions = x_samples.shape[1]
    
        assert (len(center) == dimensions),  
                'Number of center coordinates have to match sample dimensions'
        k = 0
        for x in x_samples:
            is_inside = 1
            for axis,center_point in zip(x, center):
                if np.abs(axis-center_point) > (h/2):
                    is_inside = 0
            k += is_inside
        return (k / len(x_samples)) / (h**dimensions)
    
    print('p(x) =', parzen_window_est(X_all, h=1))
    
    6 is used. See Notes for more details.

Lưu ý Khởi tạo một ví dụ

def parzen_window_est(x_samples, h=1, center=[0,0,0]):
    '''
    Implementation of the Parzen-window estimation for hypercubes.

    Keyword arguments:
        x_samples: A 'n x d'-dimensional numpy array, where each sample
            is stored in a separate row.
        h: The length of the hypercube.
        center: The coordinate center of the hypercube

    Returns the probability density for observing k samples inside the hypercube.

    '''
    dimensions = x_samples.shape[1]

    assert (len(center) == dimensions),  
            'Number of center coordinates have to match sample dimensions'
    k = 0
    for x in x_samples:
        is_inside = 1
        for axis,center_point in zip(x, center):
            if np.abs(axis-center_point) > (h/2):
                is_inside = 0
        k += is_inside
    return (k / len(x_samples)) / (h**dimensions)

print('p(x) =', parzen_window_est(X_all, h=1))
1 yêu cầu một mảng numpy trong đó các mẫu khác nhau được đặt hàng theo các cột và trong đó các hàng phản ánh kích thước của bộ dữ liệu - đây là lý do tại sao chúng ta phải truyền dữ liệu đào tạo được tạo trước đó của chúng tôi ở dạng được chuyển đổi.

Trước tiên, hãy xem nhanh cách phương thức Gaussian_kde () hoạt động bằng cách sử dụng vô hướng đơn giản làm chiều rộng cửa sổ, giống như chúng ta đã làm với kernel HyperCube trước đó và ước tính mật độ ở trung tâm.

def window_function(x_vec, unit_len=1):
"""
Implementation of the window function. Returns 1 if 3x1-sample vector
lies within a origin-centered hypercube, 0 otherwise.

"""
for row in x_vec:
    if np.abs(row) > (unit_len/2):
        return 0
return 1
5

5.3 So sánh hạt nhân Gaussian và HyperCube cho chiều rộng cửa sổ tùy ý # #

Bây giờ chúng ta hãy so sánh hạt nhân Gaussian với HyperCube cho cùng một chiều rộng cửa sổ được chọn tùy ý:

def window_function(x_vec, unit_len=1):
"""
Implementation of the window function. Returns 1 if 3x1-sample vector
lies within a origin-centered hypercube, 0 otherwise.

"""
for row in x_vec:
    if np.abs(row) > (unit_len/2):
        return 0
return 1
6

def window_function(x_vec, unit_len=1):
"""
Implementation of the window function. Returns 1 if 3x1-sample vector
lies within a origin-centered hypercube, 0 otherwise.

"""
for row in x_vec:
    if np.abs(row) > (unit_len/2):
        return 0
return 1
7

5.4 So sánh các tính toán ước tính băng thông khác nhau cho hạt nhân Gaussian #

Lớp

import numpy as np

# Generate 10,000 random 2D-patterns
mu_vec = np.array([0,0])
cov_mat = np.array([[1,0],[0,1]])
x_2Dgauss = np.random.multivariate_normal(mu_vec, cov_mat, 10000)

print(x_2Dgauss.shape)
1 đi kèm với 2 tính toán ước tính của nhóm nhạc khác nhau, chúng ta hãy khám phá nếu nó tạo ra sự khác biệt khi chọn cái này trên bộ dữ liệu của chúng ta:

def window_function(x_vec, unit_len=1):
"""
Implementation of the window function. Returns 1 if 3x1-sample vector
lies within a origin-centered hypercube, 0 otherwise.

"""
for row in x_vec:
    if np.abs(row) > (unit_len/2):
        return 0
return 1
8

def window_function(x_vec, unit_len=1):
"""
Implementation of the window function. Returns 1 if 3x1-sample vector
lies within a origin-centered hypercube, 0 otherwise.

"""
for row in x_vec:
    if np.abs(row) > (unit_len/2):
        return 0
return 1
9

6 vẽ các ước tính từ các hạt khác nhau #

Và cuối cùng, chúng ta hãy vẽ các kết quả cho các phương pháp ước tính băng thông kernel Gaussian khác nhau cho phân phối ước tính.

X_all = np.vstack((X_inside,X_outside))
assert(X_all.shape == (10,3))

k_n = 0
for row in X_all:
    k_n += window_function(row.reshape(3,1))

print('Points inside the hypercube:', k_n)
print('Points outside the hybercube:', len(X_all) - k_n)
0

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

6.1 Hiệu ứng chiều rộng cửa sổ: Đỉnh địa phương và tính trung bình #

Như chúng ta đã thảo luận trong một phần trước đó, việc chọn một chiều rộng cửa sổ thích hợp có thể là một nhiệm vụ đầy thách thức, nếu chúng ta chọn một chiều rộng cửa sổ quá nhỏ, chúng ta sẽ kết thúc với các đột biến cục bộ trong mật độ và nếu chúng ta chọn chiều rộng cửa sổ mà là quá lớn, chúng tôi sẽ tính trung bình trên toàn bộ phân phối:

X_all = np.vstack((X_inside,X_outside))
assert(X_all.shape == (10,3))

k_n = 0
for row in X_all:
    k_n += window_function(row.reshape(3,1))

print('Points inside the hypercube:', k_n)
print('Points outside the hybercube:', len(X_all) - k_n)
1

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

X_all = np.vstack((X_inside,X_outside))
assert(X_all.shape == (10,3))

k_n = 0
for row in X_all:
    k_n += window_function(row.reshape(3,1))

print('Points inside the hypercube:', k_n)
print('Points outside the hybercube:', len(X_all) - k_n)
2

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

7 Sử dụng ước tính mật độ hạt nhân cho nhiệm vụ phân loại mẫu #

Trong phần giới thiệu, tôi đã đề cập rằng một ứng dụng phổ biến của kỹ thuật Parzen-Window là ước tính mật độ điều kiện của lớp (hoặc cũng thường được gọi là 'khả năng') P (x* |)* trong một vấn đề phân loại mẫu được giám sát từ bộ dữ liệu đào tạo (trong đó X là một mẫu đa chiều thuộc lớp cụ thể ωi). Bây giờ, chúng ta hãy sử dụng ước tính mật độ kernel để thiết kế một trình phân loại Bayes đơn giản.x* | ω)* in a supervised pattern classification problem from the training dataset (where x is a multi-dimensional sample that belongs to particular class ωi).
Now, let us use the kernel density estimation for designing a simple Bayes-classifier.

Quy tắc Bayes

Để thiết kế trình phân loại lỗi tối thiểu, chúng tôi sẽ sử dụng quy tắc Bayes,:

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Quy tắc quyết định

Trong đó xác suất sau được sử dụng để xác định quy tắc quyết định của chúng tôi. Ví dụ: đối với một vấn đề 2 lớp đơn giản với hai nhãn lớp 1 và 2:

Quyết định 1 nếu P (1 | *x)> P (ω2 | x), nếu không, quyết định *2*x ) > P(ω2 | x ), else decide *ω2

Hàm mục tiêu

Đối với ví dụ này, chúng ta hãy đơn giản hóa vấn đề một chút. Chúng tôi sẽ giả sử rằng chúng tôi có xác suất trước bằng nhau (xác suất gặp phải một lớp cụ thể là bằng nhau): P (1 | * x) * = P (ω2 | * x) * = 1/n
P(ω1 | *x )* = P(ω2 | *x )* = … = P(ω1 | *x )* = 1/n

Và vì p (x) chỉ là một yếu tố tỷ lệ bằng nhau cho tất cả các xác suất sau, chúng ta có thể thả nó từ phương trình.x) is just a scale factor that is equal for all posterior probabilities, we can drop it from the equation.

Bây giờ, chúng ta có thể đơn giản hóa quy tắc quyết định, để nó chỉ phụ thuộc vào các linh mục. Đối với một vấn đề 2 lớp, điều này sẽ là

Quyết định 1 nếu P (1 | *x)> P (ω2 | x), nếu không, quyết định *2*x ) > P(ω2 | x ), else decide *ω2

Hàm mục tiêu

Đối với ví dụ này, chúng ta hãy đơn giản hóa vấn đề một chút. Chúng tôi sẽ giả sử rằng chúng tôi có xác suất trước bằng nhau (xác suất gặp phải một lớp cụ thể là bằng nhau): P (1 | * x) * = P (ω2 | * x) * = 1/n
ωj -> max[P(ω1 | *x )] for *j = 1, 2, …, c

Và vì p (x) chỉ là một yếu tố tỷ lệ bằng nhau cho tất cả các xác suất sau, chúng ta có thể thả nó từ phương trình.

Bây giờ, chúng ta có thể đơn giản hóa quy tắc quyết định, để nó chỉ phụ thuộc vào các linh mục. Đối với một vấn đề 2 lớp, điều này sẽ là

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Bayes Classifier #

X_all = np.vstack((X_inside,X_outside))
assert(X_all.shape == (10,3))

k_n = 0
for row in X_all:
    k_n += window_function(row.reshape(3,1))

print('Points inside the hypercube:', k_n)
print('Points outside the hybercube:', len(X_all) - k_n)
3

X_all = np.vstack((X_inside,X_outside))
assert(X_all.shape == (10,3))

k_n = 0
for row in X_all:
    k_n += window_function(row.reshape(3,1))

print('Points inside the hypercube:', k_n)
print('Points outside the hybercube:', len(X_all) - k_n)
4

X_all = np.vstack((X_inside,X_outside))
assert(X_all.shape == (10,3))

k_n = 0
for row in X_all:
    k_n += window_function(row.reshape(3,1))

print('Points inside the hypercube:', k_n)
print('Points outside the hybercube:', len(X_all) - k_n)
5

X_all = np.vstack((X_inside,X_outside))
assert(X_all.shape == (10,3))

k_n = 0
for row in X_all:
    k_n += window_function(row.reshape(3,1))

print('Points inside the hypercube:', k_n)
print('Points outside the hybercube:', len(X_all) - k_n)
6

X_all = np.vstack((X_inside,X_outside))
assert(X_all.shape == (10,3))

k_n = 0
for row in X_all:
    k_n += window_function(row.reshape(3,1))

print('Points inside the hypercube:', k_n)
print('Points outside the hybercube:', len(X_all) - k_n)
7

X_all = np.vstack((X_inside,X_outside))
assert(X_all.shape == (10,3))

k_n = 0
for row in X_all:
    k_n += window_function(row.reshape(3,1))

print('Points inside the hypercube:', k_n)
print('Points outside the hybercube:', len(X_all) - k_n)
8

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Và nói chung hơn (đối với nhiều lớp), trình phân loại của chúng tôi trở thành ωj -> max [p (1 | *x)] cho *j = 1, 2, triệt, c, c

7.1 Tạo bộ dữ liệu đào tạo và kiểm tra mẫu #

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

Chúng ta hãy tạo dữ liệu 2 chiều ngẫu nhiên cho 3 lớp từ phân phối Gaussian đa biến với các tham số sau:

Bây giờ, chúng tôi sẽ tạo 120 mẫu ngẫu nhiên cho mỗi trong số 3 lớp và chia nó thành một tập dữ liệu thử nghiệm và đào tạo có kích thước bằng nhau, để mỗi bộ sẽ chứa 30 mẫu cho mỗi lớp. 7.2 Thực hiện trình phân loại bằng quy tắc quyết định của Bayes, # )] for *j = 1, 2, …, c

X_all = np.vstack((X_inside,X_outside))
assert(X_all.shape == (10,3))

k_n = 0
for row in X_all:
    k_n += window_function(row.reshape(3,1))

print('Points inside the hypercube:', k_n)
print('Points outside the hybercube:', len(X_all) - k_n)
9

Bây giờ, chúng ta hãy thực hiện phân loại. Để tóm tắt lại:

Chúng ta có thể loại bỏ các xác suất trước đó (các linh mục bằng nhau) và hệ số tỷ lệ:

ωj -> Max [*P (ω1

x)] cho *j = 1, 2,…, c

7.3 Ước tính mật độ thông qua kỹ thuật Parzen-Window với hạt nhân Gaussian #

Points inside the hypercube: 3
Points outside the hypercube: 7
1

Points inside the hypercube: 3
Points outside the hypercube: 7
2

Points inside the hypercube: 3
Points outside the hypercube: 7
3

Hoặc sự thuận tiện của chúng tôi, chúng tôi hãy sử dụng lớp KDE thư viện Points inside the hypercube: 3 Points outside the hypercube: 7 6 để ước tính mật độ hạt nhân:

Points inside the hypercube: 3
Points outside the hypercube: 7
0

Hướng dẫn parzen-window classifier python - phân loại parzen-window python

7.4 Phân loại dữ liệu kiểm tra và tính toán tỷ lệ lỗi #

Points inside the hypercube: 3
Points outside the hypercube: 7
4

Points inside the hypercube: 3
Points outside the hypercube: 7
5



Bây giờ, đã đến lúc phân loại dữ liệu kiểm tra và tính toán lỗi thực nghiệm.