Các nhà khoa h cọ dữ li uệ... Học máy và ứng dụng Triển khai giải thuật K-NN5.2... Học máy và ứng dụng Triển khai giải thuật K-NNB ng ả 2... Học máy và ứng dụng Triển khai giải thuật K-N
GI I Ớ THI U Ệ K-NEAREST NEIGHBORS (K-NN)
THU T Ậ TOÁN K-NN LÀ GÌ
“Hãy cho tôi bi t b n c a b n là ai, tôi sẽ cho b n bi t b n là ngế ạ ủ ạ ạ ế ạ ười như th nào.” – đây là ý tế ưởng c a K-NN.ủ
K-NN là m tộ trong nh ngữ thu tậ toán supervised-learning đ nơ gi nả nh tấ (mà hi uệ quả trong m tộ vài trường h p)ợ trong Machine Learning Thu tậ toán có m c đíchụ phân lo iạ l pớ cho m tộ m uẫ m iớ (query point) d aự trên các thu cộ tính và l p c a các m u s n có (training data), các m u này đớ ủ ẫ ẵ ẫ ược n m trongằ m t h g i là không gian m u Khi training, thu t toán nàyộ ệ ọ ẫ ậ không h cọ m tộ đi u gì t d li u training (đây cũng là lý do thu t toán này đề ừ ữ ệ ậ ượ ếc x p vào lo iạ lazy learning), m i tính toán đọ ược th c hi n khi nó c n d đoán k t qu c aự ệ ầ ự ế ả ủ d li u m i K-NN có thữ ệ ớ ể áp d ngụ được vào cả hai lo iạ c aủ bài toán Supervised learning là Classification và Regression K-NN còn đượ ọc g i là m tộ thu t toánậ Instance- based hay Memory-based learning.
M tộ đ iố tượng được phân loại dựa vào k lân cận của nó và là một m tộ số nguyên dương được xác định trước khi thực hiện thuật toán Khoảng cách Euclidean thường được sử dụng để tính khoảng cách giữa các đối tượng trong K-NN.
MÔ T THU T Ả Ậ TOÁN K-NN
Mẫu được mô tả bằng n chiều thể hiện tính chất số, cho phép mỗi mẫu địa điểm trong không gian n chiều được xác định rõ ràng Nhờ đó, tất cả các mẫu độ đều được lưu trữ trong một mô hình không gian n chiều.
Các bước th cự hi nệ c aủ thu tậ toán K-NN được mô tả như sau:
- Xác đ nhị giá tr tham s k (s lân c nị ố ố ậ g nầ nh t)ấ
- Tính kho ng cách gi a các đ i tả ữ ố ượng c n ph n l p (query point) v iầ ầ ớ ớ t tấ cả các đ iố tượng trong training data (thường sử d ngụ kho ngả cách Euclidean)
- S p x p kho ng cách theo th t tăng d n và xác đ nh k lân c n g nắ ế ả ứ ự ầ ị ậ ầ nh t v i query point.ấ ớ
- L yấ t tấ cả các l pớ c aủ k lân c nậ g nầ nh tấ đã xác đ nh.ị
- D a vào ph n l n l p c a lân c n g n nh t đ xác đ nh l p cho m uự ầ ớ ớ ủ ậ ầ ấ ể ị ớ ẫ m i (query point).ớ Để hi uể rõ K-NN được dùng để phân l p nh thớ ư ế nào ta xem minh hoạ dưới đây:
Trong hình ảnh, dữ liệu huấn luyện được biểu diễn bằng hình tròn màu vàng và màu tím, trong khi điểm truy vấn được xác định là hình ngôi sao màu đỏ Nhiệm vụ là dự đoán lớp của điểm truy vấn dựa vào vị trí của nó trong không gian Nói cách khác, chúng ta cần xác định xem điểm truy vấn thuộc về lớp hình tròn màu vàng hay màu tím.
3 – lân c nậ g nầ nh t:ấ k tế quả là hình tròn màu tím.
Lân cận ngắn nhất (2 vàng, 2 tím) không xác định được lặp cho địa tạng, vì số lượng lân cận ngắn nhất là 2, trong đó 2 là lặp hình tròn màu vàng.
2 là l p hình tròn màu tím Nói khác h n là không có l p nào có s đ i tớ ơ ớ ố ố ượng nhi u h n l p kia Vì v y s k thề ơ ớ ậ ố ường được ch n sẽ là m t s l ọ ộ ố ẻ
6 – lân c n g n nh t: k t qu là vàng vì có 4 đ i tậ ầ ấ ế ả ố ượng thu c vàng và chộ ỉ có 2 đ i tố ượng thu c tím.ộ
Hình 2 K-NN v iớ giá trị nhi uễ
Bài toán phân loại sử dụng K-NN với dữ liệu được gán nhãn theo màu sắc Mỗi điểm dữ liệu sẽ được xác định vị trí trong không gian màu, và có thể thấy rằng một số điểm thuộc về các vùng màu khác nhau Việc kiểm tra dữ liệu trong các vùng này có thể dẫn đến nhiều khả năng sai lệch trong kết quả phân loại, do sự phân tán của các điểm dữ liệu K-NN với các giá trị khác nhau sẽ ảnh hưởng đến độ chính xác của kết quả phân loại.
ĐỘ ĐO KHO NG Ả CÁCH
EUCLIDEAN
Kho ngả cách Euclidean c aủ m tộ đi mể trong không gian P n chi uề đ nế g cố t a đ đọ ộ ược tính b ng căn b c hai c a t ng bình phằ ậ ủ ổ ương các t a đ thành ọ ộ ph n:ầ
! " # Đây cũng chính là đ dài c aộ ủ vector n iố từ g cố t aọ độ đ nế đi mể V iP ớ hai đi m ể P và Q, ta có kho ng cách Euclidean gi a chúng nh sau:ả ữ ư
Khoảng cách Euclidean là phương pháp tính toán độ dài giữa các điểm khác nhau trong không gian, giúp xác định mối quan hệ giữa các điểm một cách chính xác.
MANHATTAN
Khoảng cách Manhattan, hay còn gọi là khoảng cách L1, là một phương pháp đo lường khoảng cách giữa hai điểm trong không gian Euclid Phương pháp này dựa trên hệ tọa độ Descartes và được tính bằng tổng chiều dài của các đoạn thẳng nối giữa hai điểm trong hệ trục tọa độ này.
T a đ 2 đi mọ ộ ể A(x , y ) và B(x , y ) khi đó kho ng cách Manhattan gi a 2A A B B ả ữ đi m nh sau:ể ư d(A, B) = |x − x | + |y − y |A B A B
TÌM K LÂN C N Ậ G N Ầ NH T Ấ
Trong K-NN, vi c xác đ nh s k ban đ u phù h p là đi u không h d dàng.ệ ị ố ầ ợ ề ề ễ
Giá trị dữ liệu có thể ảnh hưởng lớn đến hiệu quả kinh tế, trong khi giá trị thấp sẽ làm tăng chi phí tính toán Các nhà khoa học dữ liệu thường chọn kỹ thuật lập mô hình và một phương pháp đánh giá hiệu suất, trong đó n là số mẫu dữ liệu.
TÍNH TOÁN Đ CHÍNH XÁC Ộ
Để đánh giá độ chính xác của thuật toán KNN classifier, chúng ta cần xem xét số lượng điểm trong dữ liệu kiểm tra mà thuật toán dự đoán đúng Số lượng này được chia cho tổng số lượng điểm trong tập dữ liệu kiểm tra để tính ra độ chính xác.
ÁP D NG Ụ K-NN VÀO PHÂN L P Ớ HOA IRIS
Đ NH Ị NGHĨA BÀI TOÁN
Hình 4 Bài toán ph n l p hoaầ ớ Iris
Việc xác định loài hoa Iris có thể thực hiện mà không cần phân tích gen hay sinh học phức tạp Thay vào đó, chúng ta có thể dựa vào các dữ liệu có sẵn và đặc điểm hình thái của từng cá thể hoa Bằng cách sử dụng các phương pháp tính toán đơn giản trên máy tính, ta có thể nhanh chóng nhận biết cá thể hoa đang xét thuộc loài Iris nào.
THU TH P Ậ VÀ TI N Ề XỬ LÝ D LI U Ữ Ệ
The Iris flower data was collected by Edgar Anderson, a prominent botanist, and subsequently analyzed and refined by Ronald Aylmer Fisher, who focused on various characteristics of the species.
- B nố thu cộ tính ki uể s :ố
■ Chi uề dài đài hoa
■ Chi uề r ngộ đài hoa
■ Chi uề dài cánh hoa
■ Chi uề r ngộ cánh hoa
- M tộ thu cộ tính còn l iạ là tên c aủ loài Iris
Trong t pậ dữ li uệ Iris, các giá trị nh nh t,ỏ ấ trung bình và l nh tớ ấ ngứ v iớ các thu c tính l n lộ ầ ượt nh sau:ư
B ngả 1 Giá tr trongị t pậ d li uữ ệ Iris
Giá tr nh ị ỏ nh tấ
Chi uề dài đài hoa 4.3 7.9 5.84
Chi uề r ngộ đài hoa 2.0 4.4 3.05
Chi uề dài cánh hoa 1.0 6.9 3.76
Chi uề r ngộ cánh hoa 0.1 2.5 1.20
Tỷ l phân chia cho m iệ ỗ loài trong ba loài Iris là 33.33%
5.2.1 Làm s ch ạ d ữ li u ệ (data cleaning)
Khi xảy ra sự thiếu thông tin về một thuộc tính nào đó trong bộ dữ liệu, số lượng dòng dữ liệu chia đều cho ba loài hoa đã có là 33.33% Nếu số lượng dòng thiếu là ít, ta có thể áp dụng phương pháp loại bỏ Trong trường hợp cần điền giá trị thiếu, ta có thể sử dụng các giá trị trung bình đã đề cập ở trên.
Khi xử lý dữ liệu, nếu giá trị bất thường vượt qua các giá trị biên đã được thống kê, chúng ta có thể xác định giá trị đó là các giá trị ngoại lệ.
Việc tích hợp và xử lý dữ liệu từ Iris là cần thiết do dữ liệu này được thu thập từ một nguồn duy nhất Các thuộc tính của dữ liệu đã được lặp lại và không có mối quan hệ tương quan nào giữa chúng Các thuộc tính đã được rút gọn chặt chẽ, do đó không cần thiết phải phân tích sâu hơn với tập dữ liệu Iris này.
Vị trí hoa Iris có vai trò quan trọng trong việc chuẩn hóa dữ liệu trong khoảng giá trị [0, 1] Điều này giúp cân bằng dữ liệu, đảm bảo không có thuộc tính nào mang giá trị lớn hơn hoặc nhỏ hơn, từ đó ảnh hưởng tích cực đến các thuộc tính còn lại trong tập dữ liệu.
5.2.4 Chu n ẩ hoá d ữ li u ệ (data normalization)
Khi có nhiều thuộc tính trong dữ liệu, sự khác biệt giữa các thuộc tính này có thể ảnh hưởng đến kết quả phân tích Để đạt được kết quả chính xác hơn, kỹ thuật chuẩn hóa dữ liệu (Data Normalization) thường được sử dụng nhằm đưa các thuộc tính về cùng một thang đo, thường là từ 0 đến 1, trước khi thực hiện KNN Có nhiều phương pháp chuẩn hóa khác nhau, không chỉ áp dụng cho KNN mà còn cho nhiều thuật toán khác Hãy cùng theo dõi bảng giá trị bên dưới để thấy rõ điều này.
Trích t b d li uừ ộ ữ ệ hoa Iris, giá trị các thu cộ tính trước và sau khi chu nẩ hoá d ữli uệ
B ngả 2 Dữ li uệ minh hoạ trước khi chu nẩ hoá
Chi uề dài đài hoa
Chi uề r ng đài ộ hoa
Chi uề dài cánh hoa
Chi uề r ng ộ cánh hoa
(Đi m dể ữ li u c nệ ầ phân lo i)ạ
B ngả 3 Kho ngả cách minh hoạ trước khi chu nẩ hoá
Tên loài Kho ngả cách
Việc dữ liệu chưa được chuẩn hóa và dễ thay đổi có thể dẫn đến sự phụ thuộc vào các điểm mang giá trị sai lệch, điều này khiến cho kết quả phân lập có thể trở nên không chính xác.
B ngả 4 Dữ li uệ minh hoạ sau khi chu nẩ hoá
Chi uề dài đài hoa
Chi uề r ng đài ộ hoa
Chi uề dài cánh hoa
Chi uề r ng ộ cánh hoa
5.1/7.0 = 0.73 3.5/3.8 = 0.92 1.4/6.0 = 0.23 0.2/2.5 = 0.08 Setosa 4.7/7.0 = 0 67 3.2/3.8 = 0.84 1.3/6.0 = 0.22 0.2/2.5 = 0.08 Setosa 7.0/7.0 = 1 3.2/3.8 = 0.84 4.7/6.0 = 0.78 1.4/2.5 = 0.56 Versicolor 6.3/7.0 = 0.9 3.3/3.8 = 0 87 6.0/6.0 = 1 2.5/2.5 = 1 Virginica 5.9/7.0 = 0.84 3.0/3.8 = 0.79 4.2/6.0 = 0.7 1.5/2.5 = 0.6 Versicolor 5.1/7.0 = 0.73 3.8/3.8 = 1 1.6/6.0 = 0.27 0.2/2.5 = 0.08 ???
B ngả 5 Kho ngả cách minh ho sauạ khi chu nẩ hoá
Tên loài Kho ngả cách
Khi k = 3, khoảng cách nhấn mạnh giữa các loài được xác định là 0.008, 0.178 và 0.715, tương ứng với tên loài Setosa, Setosa và Versicolor Trong đó, có hai lần xuất hiện gần nhất là Setosa và một lần là Versicolor, cho thấy rằng loài được phân loại chủ yếu là Setosa.
Chọn k = 4, ta có hai lần xuất hiện của loài Setosa và hai lần của loài Versicolor, vì vậy không cần phải lo lắng về việc phân loại chính xác.
V i d li u sau khi đớ ữ ệ ược chu n hoá, vi c tính toán kho ng cách sẽ cho k t quẩ ệ ả ế ả chính xác h n khi không có s ph thu c vào đ n v hay giá tr thu c tínhơ ự ụ ộ ơ ị ị ộ
TRI N Ể KHAI PHÂN L P Ớ HOA IRIS
Bộ dữ liệu hoa Iris là một tập hợp dữ liệu phong phú, bao gồm thông tin về ba loài hoa Iris khác nhau: Iris setosa, Iris virginica và Iris versicolor Mỗi loài chứa 50 mẫu hoa được đo lường với bốn thông tin chính: chiều dài và chiều rộng của đài hoa (sepal), cùng với chiều dài và chiều rộng của cánh hoa (petal).
Hình 5 Giá tr m u 3 dòngị ẫ d li uữ ệ Iris
Dataset không chứa dữ liệu thiếu hoặc null, bao gồm 150 mẫu dữ liệu Phân bố dữ liệu trong dataset cho thấy không có hiện tượng mất cân bằng dữ liệu.
Giá trị của các đặc trưng trong tập dữ liệu có sự chênh lệch lớn, ví dụ như 'SepalLength' có giá trị tối đa là 150, trong khi 'PetalWidth' chỉ có giá trị tối đa là 2.5 Do đó, việc chuẩn hóa dữ liệu về khoảng giá trị [0, 1] là cần thiết Nhóm nghiên cứu sẽ so sánh kết quả độ chính xác của mô hình khi không chuẩn hóa và sau khi đã chuẩn hóa dữ liệu đầu vào.
B ngả 6 Giá trị đ c tr ngặ ư chênh l chệ
Hình 6 S tự ương quan phân bố d li uữ ệ theo thu cộ tính
Loài hoa nhãn là một loại cây có giá trị kinh tế cao Việc nghiên cứu và phân loại loài hoa này rất quan trọng để phát triển mô hình phân loại KNN Mô hình này giúp cải thiện độ chính xác trong việc nhận diện và phân loại các giống hoa nhãn khác nhau.
PH ƯƠ NG PHÁP CH N Ọ SỐ K THÍCH H P Ợ
Bước 1: Phân dữ li uệ ng uẫ nhiên theo hai t pậ hu nấ luy nệ và ki mể tra
Bước 2: Đánh giá mô hình qua t pậ ki mể tra
5.3 Phương pháp ch nọ số k thích h pợ
Hình 7 Ch n sọ ố k thích h pợ
K-NN V I Ớ TR NG Ọ SỐ
Trong kỹ thuật đánh giá, mọi điểm dữ liệu trong 10 điểm nhỏ nhất đều có vai trò và giá trị phiếu bầu như nhau, dẫn đến sự không công bằng Rõ ràng, những điểm gần nhau có trọng số cao hơn, vì khi khoảng cách càng nhỏ thì độ chính xác càng cao Do đó, cần đánh giá khác nhau cho từng điểm trong 10 điểm nhỏ nhất này Cách đánh giá phải thỏa mãn điều kiện rằng một điểm dữ liệu gần với dữ liệu thử nghiệm thì phải được đánh giá cao hơn, đảm bảo độ tin cậy Cách đơn giản nhất là lấy nhãn của điểm dữ liệu trong training data khi dữ liệu thử nghiệm trùng với một điểm trong training data, để tránh việc đánh giá bằng 0.
Trong phần triển khai KNN của tài liệu này, một cách đánh giá khác được sử dụng là công thức sau: trong đó x là dữ liệu kiểm tra, xi là một điểm trong K-lân cận của x, wi là trọng số của điểm đó (đối với điểm dữ liệu đang xét x), và σ là một mức độ ổn định Điều này đảm bảo rằng trọng số sẽ cao hơn khi điểm xi gần gũi với x, với giá trị tối đa là 1.
7 SO SÁNH K T Ế QU V I Ả Ớ THƯ VI N Ệ SKLEARN
V i k = 7, đ chính xác khi s d ng th vi n sklearn đúng b ng v i gi i thu tớ ộ ử ụ ư ệ ằ ớ ả ậ tri n khai K-NN bên trênể
Hình 8 Tìm s k thích h p theoố ợ th vi nư ệ sklearn
8 K T Ế LU N Ậ Ưu đi mể c aủ thu tậ toán K-NN
- Độ ph cứ t pạ tính toán c aủ quá trình training là b ngằ 0.
- Dễ tri nể khai và sử d ng.ụ
- Vi cệ dự đoán k tế quả ả c dữ li uệ m iớ dễ dàng.
- Không c nầ giả sử gì về phân ph iố c aủ các class Nhược đi m c a thu t toán K-NNể ủ ậ
- KNN nhi uễ dễ đ aư ra k tế quả không chính xác khi k được ch nọ nh ỏ
- KNN c n ph i nh t t c các đi m d li u training d n đ n c n ầ ả ớ ấ ả ể ữ ệ ẫ ế ầ không gian l u tr t p hu n luy n khi d li u hu n luy n l n.ư ữ ậ ấ ệ ữ ệ ấ ệ ớ
- KNN sẽ t nố chi phí tính toán khi số lượng ki mể thử tăng lên nhi u.ề
Gi iả thu tậ KNN được nhóm tri nể khai trên môi trường Google Colab.
Link mã ngu n: ồ Tham kh oả t i đâyạ
9.1 Cài đ tặ các thư vi nệ c nầ thi tế
M tộ số th vi nư ệ c nầ thi tế được dùng trong bài g m:ồ
Thư vi nệ pandas dùng đ load d li uể ữ ệ dưới d ngạ b ngả (csv).
Thư vi nệ numpy dùng đ h tr tính toán ma tr n.ể ỗ ợ ậ
Thư vi nệ sklearn dùng đ ki mể ể tra so sánh k tế qu v iả ớ gi iả thu tậ hi nệ th c.ự
Thư vi nệ matplotlib và seaborn cho tr cự quan dữ li u.ệ
9.2 Xây d ngự l pớ mô hình K-NN
The team developed a K-nearest neighbors classifier using parameters such as the number of nearest neighbors (n_neighbors) and the distance metric (metric), which can be set to 'euclidean' or 'manhattan' Additionally, the weighting method (weights) can be configured to 'uniform', 'distance', or a custom weight function.
Vi c xây d ng l p mô hình sẽ giúp vi c kh i t o và tái s d ng mô hình dệ ự ớ ệ ở ạ ử ụ ễ dàng h n.ơ
Hàm fit(self, X, y): Giúp đ aư dữ li uệ hu nấ luy nệ vào mô hình.
V i Xớ is a method for extracting specific values from a dataset, particularly for data classification tasks It utilizes a feature vector for data representation The dataset will be transformed into a structured format consisting of distinct values and corresponding labels Essential libraries for this process include pandas for data manipulation, numpy for numerical operations, and matplotlib for data visualization, along with seaborn for enhanced graphical representation.
Hàm _calculate_distances(self, X): Tính toán kho ngả cách c a các đi m d li u c n d đoán v i các đi m d li u trong t p hu nủ ể ữ ệ ầ ự ớ ể ữ ệ ậ ấ luy n.ệ
Hàm _get_k_neighbors(self, X): Tr v kho ngả ề ả cách và chỉ số th t trong t p d li u hu n luy n c a k đi m d li u g n nh t v iứ ự ậ ữ ệ ấ ệ ủ ể ữ ệ ầ ấ ớ d li u c n d đoán.ữ ệ ầ ự
Hàm _get_weights(self, dist): Tính tr ngọ số c aủ kho ngả cách.
Hàm _weighted_mode(self, a, w, *, axis=0): Giúp b uầ ch n nhãn cho d li u c n d đoán d a theo phọ ữ ệ ầ ự ự ương pháp đánh tr ngọ s l a ố ự ch n.ọ
The `KNearestNeighborsClassifier` class is designed to implement the K-Nearest Neighbors algorithm, which classifies data points based on their proximity to other points in the dataset The constructor initializes key parameters such as the number of neighbors (`n_neighbors`), the distance metric (`metric`), and the weight function (`weights`) The `fit` method prepares the model by storing the training data in a format suitable for processing To compute distances between data points, the `_calculate_distances` method is utilized, specifically using the Euclidean distance metric when specified This structured approach ensures accurate classification based on the nearest neighbors in the dataset.
The code snippet provided focuses on calculating distances between data points using different metrics, such as Euclidean and Manhattan distances It defines methods to retrieve the k nearest neighbors based on these distances and to compute weights for these neighbors, allowing for options like uniform or distance-based weighting Additionally, the code includes a function to determine the weighted mode of the neighbors, ensuring that the most frequent values are identified based on the specified weights Finally, the predict method is designed to return predictions based on the calculated distances and weighted modes, facilitating effective decision-making in machine learning applications.
The code snippet processes input data using NumPy to retrieve neighbor distances and indices It then determines the weights for these neighbors; if no weights are provided, it calculates the mode of the fitted values based on the nearest neighbors Alternatively, if weights are available, a weighted mode is computed Finally, the resulting mode is flattened into a one-dimensional array of integers.
■ get_accuracy :hỗ tr tính toán đ chính xác c a mô hìnhợ ộ ủ b ng cách tính t l d đoán đúng c a mô hình so v i nhãn bi tằ ỉ ệ ự ủ ớ ế trước
The `draw_varying_neighbor` function calculates the accuracy of a training dataset and test set by varying the number of neighbors in a K-Nearest Neighbors classifier It visualizes how changes in the number of neighbors affect the model's performance The `get_accuracy` function determines the percentage of correct predictions by comparing the true labels with the predicted values, returning the accuracy as a percentage This process is essential for optimizing the model's parameters and improving classification results.
#Setup arrays to store training and test accuracies neighbors = np.arange( , 1 20 ) train_accuracy =np.empty ( len ( neighbors )) test_accuracy = np.empty(len(neighbors)) for i,k in enumerate(neighbors):
#Setup a knn classifier with k neighbors knn = model_class n_neighbors k ( = , weights weights = )
#Fit the model knn.fit X_train ( , y_train )
#Compute accuracy on the training set train_accuracy i [ ] = knn.score X_train ( , y_train )
To compute the accuracy of a KNN model on the test set, utilize the `knn.score` method with the test features `X_test` and true labels `y_test` The `score` function calculates the accuracy by comparing the model's predictions against the actual labels It iterates through the predicted values, counting the correct matches, and divides the total correct predictions by the number of samples to return the accuracy as a float.
9.3 Áp d ngụ mô hình K-NN vào bộ dữ li uệ Iris
Nhãn dữ liệu thuộc loại dữ liệu phân loại, vì vậy cần chuyển đổi nhãn từ kiểu ký tự sang số nguyên trước khi đưa vào mô hình.
The Iris-virginica dataset can be analyzed using various methods, including loading the dataset and examining its structure with `dataset.info()` To visualize the distribution of species, the value counts can be plotted as a bar chart using `dataset['Species'].value_counts().plot(kind='bar')` Additionally, a statistical summary can be obtained with `dataset.describe()`, and relationships between features can be explored through a pair plot generated by `sns.pairplot`, while excluding the 'Id' column and using 'Species' as the hue for better clarity.
X = dataset.drop (['Id', 'Species'], axis =1) y = dataset['Species'] from sklearn.preprocessing import LabelEncoder le = LabelEncoder() y = le.fit_transform y ( )
To visualize the impact of varying the number of neighbors in the k-NN algorithm, we generate a plot using `plt.figure` with a size of 15 by 7 The title of the plot is set to 'k-NN Varying Number of Neighbors' We then plot the testing accuracy against the number of neighbors, alongside the training accuracy, each labeled accordingly A legend is added for clarity, and the x-axis is labeled 'Number of Neighbors' while the y-axis is labeled 'Accuracy' Finally, we display the plot with `plt.show()`.
Learning/data/Iris.csv" dataset = pd.read_csv dataset_filename ( ) print(f"[INFO] Dataset shape: { dataset.shape } ) " dataset.head() kind='scatter') plt.show()
Chia t pậ dữ li uệ thành t pậ train và test tỉ lệ test_size = 20%
Chu nẩ hoá dữ li uệ
9.3.3 Xây d ng ự mô hình KNN cho t p ậ d ữ li u ệ Iris
Không có chu nẩ hoá dữ li uệ
Có chu nẩ hoá dữ li uệ
9.3.4 Thay đ i ổ giá tr ị k tìm giá tr t t ị ố nh t ấ
Không có chu nẩ hoá dữ li uệ draw_varying_neighbor X_train ( , y_train , X_test , y_test ) from sklearn.model_selection import train_test_split
To split the dataset into training and testing sets, use the `train_test_split` function with a test size of 20% and a random state of 2 Next, initialize the K-Nearest Neighbors classifier with 5 neighbors and fit the model using the training data After fitting the model, make predictions on the test set and print both the actual test labels and the predicted values Finally, calculate and display the accuracy of the model using a custom accuracy function Additionally, normalize the training data, fit the model again, and repeat the prediction and accuracy evaluation process.
X_train_norm = scaler.fit_transform X_train ( )
X_test_norm = scaler.fit_transform X_test ( )
Có chu nẩ hoá dữ li uệ draw_varying_neighbor X_train_norm ( , y_train , X_test_norm , y_test )
Ch nọ k t tố nh tấ k=1
# Tạo model (k = 1) knn_best = KNearestNeighborsClassifier n_neighbors ( =1)
# Fitting the model knn_best.fit X_train_norm ( , y_train ) predictions = knn_best.predict X_test ( ) print(y_test) print(predictions) print( "Accuracy: ", get_accuracy y_test, predictions), "%") (
9.3.5 Dùng mô hình K-NN có đánh tr ng ọ s ố
Đánh tr ngọ số “distance” cho các đi mể lân c nậ
To implement a K-Nearest Neighbors (KNN) classifier with a custom weighting function, we define a function called `myweight` that utilizes a Gaussian kernel with a parameter sigma² set to 0.5 The KNN model is initialized with three neighbors and configured to use distance-based weights After fitting the model with normalized training data, we make predictions on the normalized test set Finally, we print the actual test labels, the predicted labels, and the accuracy of the model, which is computed using the defined weighting approach.
9.4 So sánh v iớ k tế quả c aủ thư vi nệ sklearn
9.4.1 D ự đoán k t ế qu ả t p ậ test dùng mô hình Knn
The KNeighborsClassifier from sklearn achieves an impressive accuracy of 96.67% when trained on normalized training data (X_train_norm) with corresponding labels (y_train) After fitting the model, predictions are made on the normalized test data (X_test_norm), and the results, including the true labels (y_test) and predicted values, are printed Additionally, the accuracy is calculated and displayed, demonstrating the model's performance The method also showcases the use of weighted sigma to enhance prediction accuracy, further validating the effectiveness of the KNeighborsClassifier in classification tasks.
9.4.2 Thay đ i ổ k tìm giá tr ị t t ố nh t ấ
Confusion matrix cm = plot_confusion_matrix classifier ( , X_test_norm, y_test) plt.show() model_class KNeighborsClassifier = ) draw_varying_neighbor X_train_norm ( , y_train , X_test_norm , y_test ,
# Tạo model (k = 1) classifier = KNeighborsClassifier n_neighbors ( =1)
# Fitting the model classifier.fit X_train_norm ( , y_train )
# Predicting on the test set y_pred = classifier.predict X_test ( ) print(f"Labels: {y_test}") print(f"Predictions: { y_pred } ) " print(f"Accuracy is: { accuracy_score y_test, y_pred) ( *100 } %")
9.4.3 Đánh tr ng ọ s ố cho các đi m ể lân c n ậ
Đánh tr ngọ s “distance”ố cho các đi mể lân c nậ
Accuracy of 10NN (1/distance weights): 96.67 %
Đánh tr ngọ s t ố ựch nọ
K T Ế LU N Ậ
Ưu đi mể c aủ thu tậ toán K-NN
- Độ ph cứ t pạ tính toán c aủ quá trình training là b ngằ 0.
- Dễ tri nể khai và sử d ng.ụ
- Vi cệ dự đoán k tế quả ả c dữ li uệ m iớ dễ dàng.
- Không c nầ giả sử gì về phân ph iố c aủ các class Nhược đi m c a thu t toán K-NNể ủ ậ
- KNN nhi uễ dễ đ aư ra k tế quả không chính xác khi k được ch nọ nh ỏ
- KNN c n ph i nh t t c các đi m d li u training d n đ n c n ầ ả ớ ấ ả ể ữ ệ ẫ ế ầ không gian l u tr t p hu n luy n khi d li u hu n luy n l n.ư ữ ậ ấ ệ ữ ệ ấ ệ ớ
- KNN sẽ t nố chi phí tính toán khi số lượng ki mể thử tăng lên nhi u.ề
MÃ NGU N Ồ
XÂY D NG Ự L P Ớ MÔ HÌNH K-NN
The team developed a K-nearest neighbors classifier with key parameters including the number of neighbors (n_neighbors) and the distance metric (metric), which can be set to 'euclidean' or 'manhattan' Additionally, the scoring method (weights) can be configured as 'uniform', 'distance', or a custom weight function.
Vi c xây d ng l p mô hình sẽ giúp vi c kh i t o và tái s d ng mô hình dệ ự ớ ệ ở ạ ử ụ ễ dàng h n.ơ
Hàm fit(self, X, y): Giúp đ aư dữ li uệ hu nấ luy nệ vào mô hình.
The article discusses the importance of feature extraction in data analysis, particularly in transforming raw data into structured values and labels It emphasizes that the data can be converted into a comprehensive set of features and corresponding labels for effective analysis Key libraries such as Pandas, NumPy, Matplotlib, and Seaborn are essential for data manipulation and visualization, while the use of the Counter from the collections module aids in frequency analysis.
Hàm _calculate_distances(self, X): Tính toán kho ngả cách c a các đi m d li u c n d đoán v i các đi m d li u trong t p hu nủ ể ữ ệ ầ ự ớ ể ữ ệ ậ ấ luy n.ệ
Hàm _get_k_neighbors(self, X): Tr v kho ngả ề ả cách và chỉ số th t trong t p d li u hu n luy n c a k đi m d li u g n nh t v iứ ự ậ ữ ệ ấ ệ ủ ể ữ ệ ầ ấ ớ d li u c n d đoán.ữ ệ ầ ự
Hàm _get_weights(self, dist): Tính tr ngọ số c aủ kho ngả cách.
Hàm _weighted_mode(self, a, w, *, axis=0): Giúp b uầ ch n nhãn cho d li u c n d đoán d a theo phọ ữ ệ ầ ự ự ương pháp đánh tr ngọ s l a ố ự ch n.ọ
The `score` method in the KNearestNeighborsClassifier class calculates the accuracy of predictions when evaluating the model The class is initialized with parameters including the number of neighbors, distance metric, and weight type The `fit` method prepares the training data by converting the input arrays into NumPy arrays The `_calculate_distances` method computes the distances between data points, with the option to use the Euclidean metric.
The code snippet demonstrates a distance calculation method for a k-nearest neighbors (KNN) algorithm, utilizing both Euclidean and Manhattan metrics It begins by expanding the dimensions of the input data, followed by computing distances based on the selected metric The method `_get_k_neighbors` identifies the k-nearest neighbors by sorting the calculated distances The `_get_weights` function applies weights to the distances, allowing for uniform or distance-based weighting, and handles infinite distance values The `_weighted_mode` method computes the most frequent value among neighbors using the specified weights Finally, the `predict` method utilizes these calculations to generate predictions based on the input data.
To compute the predicted mode for a dataset, first convert the input data into a NumPy array and retrieve the distances and indices of the k-nearest neighbors If no weights are provided, use the most common class label among the neighbors Alternatively, if weights are available, calculate a weighted mode based on the neighbor distances Finally, return the mode as a flattened NumPy array of integers.
■ get_accuracy :hỗ tr tính toán đ chính xác c a mô hìnhợ ộ ủ b ng cách tính t l d đoán đúng c a mô hình so v i nhãn bi tằ ỉ ệ ự ủ ớ ế trước
The `draw_varying_neighbor` function calculates the accuracy of a classifier on training and testing datasets while visualizing changes in accuracy based on varying neighbor values The accuracy is determined using the `get_accuracy` function, which compares the true labels with predicted values, counting the correct predictions and returning the accuracy as a percentage This method allows for the evaluation of different configurations in the K-Nearest Neighbors algorithm, providing insights into model performance.
#Setup arrays to store training and test accuracies neighbors = np.arange( , 1 20 ) train_accuracy =np.empty ( len ( neighbors )) test_accuracy = np.empty(len(neighbors)) for i,k in enumerate(neighbors):
#Setup a knn classifier with k neighbors knn = model_class n_neighbors k ( = , weights weights = )
#Fit the model knn.fit X_train ( , y_train )
#Compute accuracy on the training set train_accuracy i [ ] = knn.score X_train ( , y_train )
To compute the accuracy on the test set using KNN, we utilize the `knn.score` method with the test data, `X_test`, and the corresponding labels, `y_test` The `score` function evaluates predictions against the actual values by iterating through each instance, counting the correct predictions The final accuracy is calculated as the ratio of correct predictions to the total number of instances in the test set, providing a clear measure of model performance.
9.3 Áp d ngụ mô hình K-NN vào bộ dữ li uệ Iris
Nhãn dữ liệu thuộc kiểu dữ liệu phân loại, vì vậy cần chuyển đổi nhãn từ dạng ký tự sang số nguyên trước khi đưa vào mô hình.
The Iris-virginica species can be analyzed using a dataset that includes essential information such as value counts for each species and descriptive statistics Visualizations can be created using bar plots to illustrate species distribution and pair plots to explore relationships between features, excluding the 'Id' column for clarity.
X = dataset.drop (['Id', 'Species'], axis =1) y = dataset['Species'] from sklearn.preprocessing import LabelEncoder le = LabelEncoder() y = le.fit_transform y ( )
To visualize the impact of varying the number of neighbors in the k-NN algorithm, a plot is generated using plt.figure with a size of 15 by 7 inches The title of the plot is set to 'k-NN Varying Number of Neighbors' The testing accuracy is represented by one line, while the training accuracy is depicted by another, both plotted against the number of neighbors A legend is included for clarity, and the x-axis is labeled 'Number of Neighbors' while the y-axis is labeled 'Accuracy' Finally, the plot is displayed using plt.show().
Learning/data/Iris.csv" dataset = pd.read_csv dataset_filename ( ) print(f"[INFO] Dataset shape: { dataset.shape } ) " dataset.head() kind='scatter') plt.show()
Chia t pậ dữ li uệ thành t pậ train và test tỉ lệ test_size = 20%
Chu nẩ hoá dữ li uệ
9.3.3 Xây d ng ự mô hình KNN cho t p ậ d ữ li u ệ Iris
Không có chu nẩ hoá dữ li uệ
Có chu nẩ hoá dữ li uệ
9.3.4 Thay đ i ổ giá tr ị k tìm giá tr t t ị ố nh t ấ
Không có chu nẩ hoá dữ li uệ draw_varying_neighbor X_train ( , y_train , X_test , y_test ) from sklearn.model_selection import train_test_split
To split the dataset into training and testing sets, use the `train_test_split` function with a test size of 20% and a random state of 2 Implement the K-Nearest Neighbors classifier by initializing it with 5 neighbors and fitting it to the training data After training the model, generate predictions on the test set and display both the actual and predicted values Finally, calculate and print the accuracy of the model's predictions Additionally, normalize the training data and repeat the fitting and prediction process to assess the model's performance on the normalized test set.
X_train_norm = scaler.fit_transform X_train ( )
X_test_norm = scaler.fit_transform X_test ( )
Có chu nẩ hoá dữ li uệ draw_varying_neighbor X_train_norm ( , y_train , X_test_norm , y_test )
Ch nọ k t tố nh tấ k=1
# Tạo model (k = 1) knn_best = KNearestNeighborsClassifier n_neighbors ( =1)
# Fitting the model knn_best.fit X_train_norm ( , y_train ) predictions = knn_best.predict X_test ( ) print(y_test) print(predictions) print( "Accuracy: ", get_accuracy y_test, predictions), "%") (
9.3.5 Dùng mô hình K-NN có đánh tr ng ọ s ố
Đánh tr ngọ số “distance” cho các đi mể lân c nậ
To implement a K-Nearest Neighbors classifier with a custom weighting function, we define the function `myweight` to adjust the influence of neighbors based on their distances, using a parameter `sigma2` set to 0.5 We then initialize the `KNearestNeighborsClassifier` with three neighbors and apply the custom weights using the 'distance' option After fitting the model with normalized training data, we make predictions on the test set and evaluate the accuracy, displaying both the true labels and predicted values along with the calculated accuracy percentage.
SO SÁNH V I Ớ K T Ế QUẢ C A Ủ THƯ VI N Ệ SKLEARN
9.4.1 D ự đoán k t ế qu ả t p ậ test dùng mô hình Knn
The KNeighborsClassifier from sklearn achieves an impressive accuracy of 96.67% when predicting outcomes based on normalized training and testing datasets After fitting the model with the training data, predictions are made on the test set, allowing for a comparison of actual versus predicted values The results highlight the model's effectiveness, as the accuracy is calculated and displayed for both standard and weighted approaches, showcasing the robustness of the KNN algorithm in classification tasks.
9.4.2 Thay đ i ổ k tìm giá tr ị t t ố nh t ấ
Confusion matrix cm = plot_confusion_matrix classifier ( , X_test_norm, y_test) plt.show() model_class KNeighborsClassifier = ) draw_varying_neighbor X_train_norm ( , y_train , X_test_norm , y_test ,
# Tạo model (k = 1) classifier = KNeighborsClassifier n_neighbors ( =1)
# Fitting the model classifier.fit X_train_norm ( , y_train )
# Predicting on the test set y_pred = classifier.predict X_test ( ) print(f"Labels: {y_test}") print(f"Predictions: { y_pred } ) " print(f"Accuracy is: { accuracy_score y_test, y_pred) ( *100 } %")
9.4.3 Đánh tr ng ọ s ố cho các đi m ể lân c n ậ
Đánh tr ngọ s “distance”ố cho các đi mể lân c nậ
Accuracy of 10NN (1/distance weights): 96.67 %
Đánh tr ngọ s t ố ựch nọ
The KNeighborsClassifier achieved an impressive accuracy of 96.67% using customized weights with 10 nearest neighbors (10NN) By setting the number of neighbors to 7 and utilizing the Euclidean distance (p = 2), the model effectively classified the data The function myweight, which applies a Gaussian weight based on the distances with a variance of sigma2 = 0.5, enhances the model's performance Additionally, a separate configuration with 5 neighbors was also tested, demonstrating the flexibility and effectiveness of the KNN algorithm in achieving high accuracy through tailored parameters.
2, weights = myweight ) knn_model_custom_weight.fit X_train_norm ( , y_train ) y_pred = knn_model_custom_weight.predict X_test_norm ( ) print("Accuracy of 10NN (customized weights): %.2f %%"
The accuracy of the K-Nearest Neighbors (KNN) model using distance weights can be calculated by applying the formula (100 * accuracy_score(y_test, y_pred)) The model is trained on normalized training data (X_train_norm) and corresponding labels (y_train) with the command knn_model_weight.fit(X_train_norm, y_train) Predictions for the test set (X_test_norm) are made using y_pred = knn_model_weight.predict(X_test) Finally, the model's accuracy is displayed with the output: "Accuracy of 10NN (1/distance weights): %.2f %%".
% (100* accuracy_score y_test ( , y_pred ))) model_class KNeighborsClassifier = , weights = 'distance') model_class KNeighborsClassifier = , weights = myweight )
Kết quả hiện thực của nhóm giống với kết quả của thư viện sklearn.