Implementation of K-Nearest Neighbors Classifier for Fish Data Analysis (물고기 데이터 분석을 위한 K-최근접 이웃 분류기 구현)


K-Nearest Neighbors Classifier Implementation for Fish Data
In this section, we initialize and prepare data related to the lengths and weights of different fish species. This data will be used to train and test a K-Nearest Neighbors (KNN) classifier. KNN is a simple, yet effective machine learning algorithm used for classification tasks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Importing the KNeighborsClassifier from the sklearn library, which provides simple and efficient tools for data mining and data analysis. from sklearn.neighbors import KNeighborsClassifier kn = KNeighborsClassifier() # Data representing the lengths of fish in centimeters. This list contains values corresponding to the lengths of individual fish. fish_length = [25.4, 26.3, 26.5, 29.0, 29.7, 30.0, 30.7, 31.0, 31.5, 32.0, 32.5, 34.0, 35.0, 36.0, 36.5, 37.0, 38.5, 39.5, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0] # Data representing the corresponding weights of the fish in grams. Each weight value in this list is paired with a fish length from the fish_length list. fish_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 475.0, 500.0, 525.0, 550.0, 575.0, 600.0, 625.0, 650.0, 675.0, 700.0, 725.0, 750.0, 775.0, 800.0, 825.0, 850.0, 875.0, 900.0, 925.0, 950.0, 975.0, 1000.0, 1025.0, 1050.0, 1075.0, 1100.0, 1125.0, 1150.0, 1175.0] # We create a 2D list named 'fish_data' where each element is a list containing the length and weight of a fish. This structure is used to store feature data in a format that can be fed into machine learning algorithms. fish_data = [[l, w] for l, w in zip(fish_length, fish_weight)] # The 'fish_target' list represents the target classification labels. In this example, the first 35 fish (represented by 1) are one species, and the remaining 14 fish (represented by 0) are another species. fish_target = [1]*35 + [0]*14 # The following commands print specific slices of the fish_data list to the console. These print statements help verify that the data has been correctly formatted and stored. print(fish_data[4]) # Prints the data for the fifth fish in the list, which includes its length and weight. print(fish_data[0:5]) # Prints the data for the first five fish in the list. print(fish_data[:5]) # Another way to print the first five fish, using shorthand notation. print(fish_data[44:]) # Prints the data for the last five fish in the list. |
This code block is the foundation for our machine learning task. We import the necessary library, prepare our fish data, and verify its structure by printing parts of the dataset. The fish data is organized into a format suitable for use in machine learning algorithms, particularly the K-Nearest Neighbors (KNN) algorithm. The target data is also set up to classify the fish into two categories based on their length and weight.
Data Preparation and Training the KNN Classifier
After initializing the data, the next step involves preparing it for use in our KNN model. This process includes converting the data into numpy arrays, shuffling the data to ensure a random distribution, and then splitting it into training and test sets. The training set is used to train the model, while the test set is used to evaluate its performance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# Importing the numpy library, which provides support for large multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. import numpy as np # Converting the fish data and target lists into numpy arrays for more efficient computation and manipulation. input_arr = np.array(fish_data) target_arr = np.array(fish_target) # Setting a random seed ensures that the random numbers generated are the same every time the code is run, allowing for reproducibility of the results. np.random.seed(42) # Generating an array of indices from 0 to 48 (since we have 49 data points) and shuffling them to randomly reorder the data. index = np.arange(49) np.random.shuffle(index) # Splitting the data into training and testing sets. The first 35 shuffled indices are used for training, while the remaining 14 are used for testing. train_input = input_arr[index[:35]] train_target = target_arr[index[:35]] # The remaining indices form the test set. This split allows us to train the model on one part of the data and test it on another, ensuring an unbiased evaluation. test_input = input_arr[index[35:]] test_target = target_arr[index[35:]] # Training the K-Nearest Neighbors model using the training data. The model will learn to associate the input features (length and weight) with the correct species classification. kn = kn.fit(train_input, train_target) # Evaluating the trained model on the test set. The score method returns the accuracy of the model, which is the proportion of correctly predicted labels. score = kn.score(test_input, test_target) print(score) # The accuracy score (between 0 and 1) indicates how well the model performs on the test data. |
This part of the implementation involves using numpy to structure and randomize the dataset. We ensure that the data is shuffled before splitting it into training and test sets. The KNN model is then trained on the training set, and its performance is evaluated on the test set by calculating the accuracy score. The accuracy score is a crucial metric that tells us how well our model is able to classify new, unseen data.
Training Set and Test Set
The training set and test set play a crucial role in machine learning, where they are used to train and evaluate a model. To put it simply, these two concepts are like preparing for an exam and actually taking the exam.
Training Set
- Purpose: The data used to train the model.
- Analogy: It’s like the textbooks and materials a student uses to study for an exam.
- Explanation: The training set provides the data and correct answers (targets) so the model can learn. The model uses this data to identify patterns and develop the ability to make predictions when it encounters new data.
Test Set
- Purpose: The data used to evaluate the performance of the model.
- Analogy: It’s like the exam that a student takes to test their knowledge after studying.
- Explanation: The test set is data that the model has never seen during training. It is used to assess how well the model can predict outcomes based on what it has learned. This stage measures the model’s accuracy.
Why do we split the data into a training set and a test set?
If we only use the training set to train and evaluate the model, the model might simply memorize the answers in the training set. This would make it difficult for the model to accurately predict new data. To prevent this, we use a separate test set, which was not used during training, to evaluate the model’s performance.
This approach helps us verify whether the model performs well on new, unseen data, ensuring it generalizes well.
Example to Understand
Training Set: Suppose we want to build a model that predicts the species of a fish based on its length and weight. First, we provide the model with data that includes these features (length, weight, and species) for various fish. This data is the training set.
Test Set: After the model has been trained, we evaluate how well it has learned by giving it new fish data that was not part of the training. We then check if the model can correctly identify the species. This new data is the test set.
By splitting the data into training and test sets, we can objectively assess how well the model is likely to perform on new, unseen data.
Visualization of Training and Test Data
Visualizing the data is an important step in understanding the distribution of the data points. In this section, we use the matplotlib library to create a scatter plot that displays the fish data from both the training and test sets. This helps us visually assess how well the data is separated and whether the model is likely to perform well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# Importing the matplotlib library, a popular Python plotting library for creating static, animated, and interactive visualizations. import matplotlib.pyplot as plt # Creating a scatter plot of the training data. The length of the fish is plotted on the x-axis, and the weight on the y-axis. The points are colored blue to distinguish them from the test data. plt.scatter(train_input[:,0], train_input[:,1], c='blue', label='Train set') # Creating a scatter plot of the test data on the same graph. These points are colored red, making it easy to compare them with the training data. plt.scatter(test_input[:,0], test_input[:,1], c='red', label='Test set') # Labeling the axes of the graph to indicate what each axis represents. The x-axis represents the fish length, and the y-axis represents the fish weight. plt.xlabel('Length') plt.ylabel('Weight') # Adding a legend to the plot to differentiate between the training and test data points. plt.legend() # Displaying the plot. This step renders the graph so that it can be visually analyzed. plt.show() |
This code block is dedicated to visualizing the dataset. By plotting the training and test data on the same graph, we can easily see how the data is distributed and whether there is a clear distinction between the two classes of fish. This visual check is an essential step in confirming that the data is correctly prepared and that the model has a good chance of accurately classifying the fish based on their length and weight.
물고기 데이터를 위한 K-최근접 이웃 분류기 구현
이 섹션에서는 다양한 물고기 종의 길이와 무게와 관련된 데이터를 초기화하고 준비합니다. 이 데이터는 K-최근접 이웃(K-Nearest Neighbors, KNN) 분류기를 훈련하고 테스트하는 데 사용될 것입니다. KNN은 분류 작업에 사용되는 간단하면서도 효과적인 기계 학습 알고리즘입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# 데이터 마이닝과 데이터 분석을 위한 간단하고 효율적인 도구를 제공하는 sklearn 라이브러리에서 KNeighborsClassifier를 가져옵니다. from sklearn.neighbors import KNeighborsClassifier kn = KNeighborsClassifier() # 물고기의 길이를 센티미터 단위로 나타낸 데이터입니다. 이 리스트에는 각 물고기의 길이에 해당하는 값들이 포함되어 있습니다. fish_length = [25.4, 26.3, 26.5, 29.0, 29.7, 30.0, 30.7, 31.0, 31.5, 32.0, 32.5, 34.0, 35.0, 36.0, 36.5, 37.0, 38.5, 39.5, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0] # 각 물고기의 무게를 그램 단위로 나타낸 데이터입니다. 이 리스트의 각 무게 값은 fish_length 리스트의 물고기 길이와 쌍을 이룹니다. fish_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 475.0, 500.0, 525.0, 550.0, 575.0, 600.0, 625.0, 650.0, 675.0, 700.0, 725.0, 750.0, 775.0, 800.0, 825.0, 850.0, 875.0, 900.0, 925.0, 950.0, 975.0, 1000.0, 1025.0, 1050.0, 1075.0, 1100.0, 1125.0, 1150.0, 1175.0] # 'fish_data'라는 이름의 2D 리스트를 생성하여 각 요소가 물고기의 길이와 무게를 포함하는 리스트입니다. 이 구조는 기계 학습 알고리즘에 입력 데이터로 사용할 수 있는 형식입니다. fish_data = [[l, w] for l, w in zip(fish_length, fish_weight)] # 'fish_target' 리스트는 목표 분류 레이블을 나타냅니다. 이 예에서는 첫 번째 35마리의 물고기(1로 표현됨)는 한 종이며, 나머지 14마리의 물고기(0으로 표현됨)는 다른 종입니다. fish_target = [1]*35 + [0]*14 # 다음 명령어는 fish_data 리스트의 특정 부분을 콘솔에 출력합니다. 이러한 출력 명령은 데이터가 올바르게 형식화되어 저장되었는지 확인하는 데 도움이 됩니다. print(fish_data[4]) # 리스트의 다섯 번째 물고기 데이터를 출력하며, 길이와 무게가 포함됩니다. print(fish_data[0:5]) # 리스트의 처음 다섯 마리 물고기 데이터를 출력합니다. print(fish_data[:5]) # 위와 동일한 기능을 하는 간단한 표기법입니다. print(fish_data[44:]) # 리스트의 마지막 다섯 마리 물고기 데이터를 출력합니다. |
이 코드 블록은 기계 학습 작업을 위한 기초입니다. 필수 라이브러리를 가져오고 물고기 데이터를 준비하며, 데이터 구조가 제대로 형성되었는지 검증하기 위해 일부 데이터를 출력합니다. 물고기 데이터는 K-최근접 이웃(KNN) 알고리즘과 같은 기계 학습 알고리즘에 적합한 형식으로 구성됩니다. 목표 데이터 또한 길이와 무게를 기준으로 물고기를 두 가지 범주로 분류할 수 있도록 설정됩니다.
데이터 준비 및 KNN 분류기 훈련
데이터를 초기화한 후, 다음 단계는 KNN 모델에서 사용할 수 있도록 데이터를 준비하는 것입니다. 이 과정에는 데이터를 numpy 배열로 변환하고, 무작위로 데이터를 섞은 후, 훈련 세트와 테스트 세트로 나누는 작업이 포함됩니다. 훈련 세트는 모델을 훈련시키는 데 사용되며, 테스트 세트는 모델의 성능을 평가하는 데 사용됩니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# 대형 다차원 배열과 행렬을 지원하며 이러한 배열에서 다양한 수학적 연산을 수행할 수 있는 numpy 라이브러리를 가져옵니다. import numpy as np # 물고기 데이터와 목표 리스트를 numpy 배열로 변환하여 연산과 조작을 보다 효율적으로 수행할 수 있도록 합니다. input_arr = np.array(fish_data) target_arr = np.array(fish_target) # 랜덤 시드를 설정하면 매번 코드를 실행할 때 생성되는 난수들이 동일하게 생성되어 결과를 재현할 수 있습니다. np.random.seed(42) # 0부터 48까지의 인덱스 배열을 생성하고 이를 섞어서 데이터를 무작위로 재배열합니다. index = np.arange(49) np.random.shuffle(index) # 데이터를 훈련 세트와 테스트 세트로 나누기 위해 섞인 인덱스를 사용합니다. 처음 35개의 인덱스는 훈련 세트에 사용되고, 나머지 14개는 테스트 세트에 사용됩니다. train_input = input_arr[index[:35]] train_target = target_arr[index[:35]] # 나머지 인덱스는 테스트 세트를 형성합니다. 이와 같은 분할 방법은 모델을 한 부분의 데이터로 훈련하고, 다른 부분의 데이터로 테스트하여 공정하게 평가할 수 있게 합니다. test_input = input_arr[index[35:]] test_target = target_arr[index[35:]] # 훈련 데이터를 사용하여 K-최근접 이웃 모델을 훈련시킵니다. 모델은 입력 특성(길이 및 무게)과 올바른 종 분류 사이의 연관성을 학습하게 됩니다. kn = kn.fit(train_input, train_target) # 훈련된 모델을 테스트 세트에서 평가합니다. score 메서드는 모델의 정확도를 반환하며, 이는 올바르게 예측된 레이블의 비율입니다. score = kn.score(test_input, test_target) print(score) # 정확도 점수(0에서 1 사이)는 모델이 테스트 데이터에서 얼마나 잘 수행했는지를 나타냅니다. |
이 구현 부분에서는 numpy를 사용하여 데이터 세트를 구조화하고 무작위화합니다. 데이터를 섞어서 훈련 세트와 테스트 세트로 나누고, KNN 모델을 훈련 세트에서 훈련시킵니다. 그 후, 테스트 세트에서 모델의 성능을 평가하고 정확도 점수를 계산합니다. 정확도 점수는 모델이 새로운 데이터를 얼마나 잘 분류할 수 있는지를 알려주는 중요한 지표입니다.
훈련 세트(Training Set)와 테스트 세트(Test Set)
훈련 세트와 테스트 세트는 머신러닝에서 모델을 학습시키고 평가하는 데 중요한 역할을 합니다. 쉽게 설명하자면, 이 두 개념은 마치 시험을 준비하는 것과 실제로 시험을 보는 과정과 비슷합니다.
훈련 세트 (Training Set)
- 목적: 모델을 학습시키기 위한 데이터입니다.
- 비유: 마치 학생이 시험을 준비할 때 공부하는 교재와 같습니다.
- 설명: 훈련 세트는 모델이 학습할 수 있도록 데이터와 정답(목표)을 제공합니다. 모델은 이 데이터를 보고 패턴을 학습하여, 새로운 데이터를 만났을 때 예측할 수 있는 능력을 키우게 됩니다.
테스트 세트 (Test Set)
- 목적: 모델의 성능을 평가하기 위한 데이터입니다.
- 비유: 학생이 공부한 내용을 시험을 통해 평가받는 것과 같습니다.
- 설명: 테스트 세트는 모델이 훈련 중에는 한 번도 보지 못한 데이터입니다. 모델이 학습한 내용을 바탕으로 이 데이터에 대해 얼마나 정확하게 예측하는지를 평가합니다. 이 단계에서 모델의 성능을 측정합니다.
왜 훈련 세트와 테스트 세트를 나누는가?
훈련 세트만 사용해서 모델을 학습하고 평가한다면, 모델이 단순히 훈련 세트의 정답을 외워버릴 위험이 있습니다. 이렇게 되면 모델은 새로운 데이터를 제대로 예측하지 못할 수 있습니다. 이를 방지하기 위해, 훈련에 사용된 데이터와는 다른 데이터로 성능을 평가하는 테스트 세트를 사용합니다.
이를 통해 모델이 새로운 데이터에서도 잘 작동하는지, 즉 일반화 능력이 있는지를 확인할 수 있습니다.
예시로 이해해보기
훈련 세트: 만약 우리가 다양한 종류의 물고기 길이와 무게를 사용하여 물고기의 종류를 예측하는 모델을 만들고 싶다면, 먼저 이 정보를 포함한 데이터(길이, 무게, 그리고 종류)를 모델에게 제공하고 학습시킵니다. 이때 사용되는 데이터가 훈련 세트입니다.
테스트 세트: 모델이 학습한 후, 우리는 모델이 얼마나 잘 학습했는지를 확인하기 위해 훈련 때 사용하지 않은 새로운 물고기 데이터를 모델에게 주고, 맞출 수 있는지 확인합니다. 이때 사용하는 데이터가 테스트 세트입니다.
훈련 세트와 테스트 세트를 나눔으로써, 우리는 모델이 실제로 새로운 데이터를 얼마나 잘 예측할 수 있는지 객관적으로 평가할 수 있습니다.
훈련 및 테스트 데이터의 시각화
데이터 시각화는 데이터 포인트의 분포를 이해하는 데 중요한 단계입니다. 이 섹션에서는 matplotlib 라이브러리를 사용하여 훈련 세트와 테스트 세트의 물고기 데이터를 표시하는 산점도를 만듭니다. 이를 통해 데이터가 얼마나 잘 분리되어 있는지, 모델이 얼마나 잘 작동할 가능성이 있는지를 시각적으로 평가할 수 있습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# 정적, 애니메이션 및 인터랙티브 시각화를 생성할 수 있는 인기 있는 Python 그래프 라이브러리인 matplotlib를 가져옵니다. import matplotlib.pyplot as plt # 훈련 데이터의 산점도를 생성합니다. 물고기의 길이는 x축에, 무게는 y축에 플로팅됩니다. 이 포인트들은 테스트 데이터와 구별하기 위해 파란색으로 색칠됩니다. plt.scatter(train_input[:,0], train_input[:,1], c='blue', label='Train set') # 동일한 그래프에 테스트 데이터의 산점도를 생성합니다. 이 포인트들은 빨간색으로 표시되어 훈련 데이터와 쉽게 비교할 수 있습니다. plt.scatter(test_input[:,0], test_input[:,1], c='red', label='Test set') # 그래프의 축에 레이블을 붙여 각 축이 무엇을 나타내는지 표시합니다. x축은 물고기 길이를, y축은 물고기 무게를 나타냅니다. plt.xlabel('Length') plt.ylabel('Weight') # 그래프에 범례를 추가하여 훈련 및 테스트 데이터 포인트를 구분할 수 있게 합니다. plt.legend() # 그래프를 표시합니다. 이 단계는 그래프를 렌더링하여 시각적으로 분석할 수 있게 합니다. plt.show() |
이 코드 블록은 데이터 세트를 시각화하는 데 전념하고 있습니다. 훈련 및 테스트 데이터를 동일한 그래프에 플로팅함으로써, 데이터가 어떻게 분포되어 있는지, 두 물고기 종이 얼마나 명확하게 구별될 수 있는지를 쉽게 확인할 수 있습니다. 이러한 시각적 검사는 데이터가 올바르게 준비되었고 모델이 정확하게 물고기를 분류할 수 있을 가능성을 확인하는 데 중요한 단계입니다.