Data Preprocessing and Machine Learning Model Building with Python (데이터 전처리 및 머신러닝 모델 구축하기 (Python 활용))


Comprehensive Analysis of Data Preprocessing and Machine Learning with Python
Introduction
This blog post provides a detailed analysis of a series of images extracted from a book on data preprocessing and machine learning with Python.
The content covers various stages of data preparation, model building, and evaluation using Python’s popular libraries, including numpy
and scikit-learn
.
The goal is to give a clear understanding of each step in the machine learning pipeline, from raw data collection to model prediction visualization.
Data Preparation and Preprocessing
Data Merging
The first step in the data preprocessing phase is merging multiple data lists into a single array. This is crucial for feeding the data into machine learning models.
The function np.column_stack()
is used to combine the fish length and weight into a two-dimensional array.
Data Splitting
After merging, the next step is to split the data into training and test sets. This ensures that the model is evaluated on data it hasn’t seen during training, which provides a realistic measure of its performance.
The train_test_split()
function from scikit-learn
is utilized, with the stratify
parameter maintaining class balance across the splits.
Model Training
Once the data is preprocessed, it is ready to be used for training a machine learning model. In this case, the K-Nearest Neighbors (KNN) classifier is chosen for its simplicity and effectiveness in certain scenarios. The model is trained on the standardized data to ensure that all features contribute equally to the prediction process.
The model’s performance is then evaluated using the test data, and accuracy scores are calculated to determine how well the model performs on unseen data.
Data Scaling
Standardization is a key step in preprocessing, particularly when the features have different units or scales. The mean and standard deviation of the training data are used to scale the data, ensuring that it has a mean of 0 and a standard deviation of 1.
This step is crucial for distance-based algorithms like KNN, where different scales can disproportionately influence the distance measurements.
Visualization
Visualization plays a critical role in understanding data distribution and model predictions. matplotlib
is used to plot the scaled training data along with a new data point, providing a visual confirmation of the model’s decision boundary.
The scatter plot helps in evaluating how well the model has learned from the data.
파이썬을 활용한 데이터 전처리 및 머신러닝의 종합 분석
소개
이 블로그 게시물은 파이썬을 활용한 데이터 전처리 및 머신러닝에 대한 책에서 추출한 일련의 이미지를 자세히 분석한 것입니다.
내용은 데이터 준비, 모델 구축 및 평가의 여러 단계를 다루며, numpy
및 scikit-learn
과 같은 파이썬의 인기 있는 라이브러리를 사용합니다.
이 포스팅의 목표는 원시 데이터 수집부터 모델 예측 시각화에 이르는 머신러닝 파이프라인의 각 단계를 명확히 이해하는 것입니다.
데이터 준비 및 전처리
데이터 병합
데이터 전처리 단계의 첫 번째 단계는 여러 데이터 리스트를 하나의 배열로 병합하는 것입니다. 이 과정은 머신러닝 모델에 데이터를 입력하는 데 필수적입니다.
np.column_stack()
함수를 사용하여 물고기의 길이와 무게를 2차원 배열로 병합합니다.
데이터 분할
병합 후 다음 단계는 데이터를 훈련 세트와 테스트 세트로 나누는 것입니다. 이는 모델이 훈련 중 보지 않은 데이터에서 평가되도록 하여 모델 성능을 현실적으로 측정할 수 있게 합니다.
scikit-learn
의 train_test_split()
함수를 사용하며, stratify
매개변수를 사용하여 클래스 균형을 유지합니다.
모델 학습
데이터가 전처리되면 머신러닝 모델 학습에 사용할 준비가 됩니다. 이 경우, K-최근접 이웃(KNN) 분류기가 간단하면서도 특정 시나리오에서 효과적이기 때문에 선택되었습니다. 모델은 표준화된 데이터를 기반으로 학습되며, 이를 통해 예측 과정에서 모든 특성이 동일하게 기여할 수 있도록 합니다.
이후 테스트 데이터를 사용해 모델의 성능을 평가하고, 정확도 점수를 계산하여 모델이 보지 않은 데이터에서 얼마나 잘 동작하는지 확인합니다.
데이터 스케일링
표준화는 특히 특성들이 서로 다른 단위나 스케일을 가질 때 전처리 과정에서 중요한 단계입니다. 훈련 데이터의 평균과 표준 편차를 사용해 데이터를 스케일링하여 평균이 0이고 표준 편차가 1이 되도록 합니다.
이 단계는 KNN과 같은 거리 기반 알고리즘에서 매우 중요하며, 서로 다른 스케일이 거리 측정에 과도한 영향을 미치는 것을 방지합니다.
시각화
시각화는 데이터 분포와 모델 예측을 이해하는 데 중요한 역할을 합니다. matplotlib
을 사용해 표준화된 훈련 데이터와 새로운 데이터 포인트를 함께 시각화하여 모델의 결정 경계를 시각적으로 확인할 수 있습니다.
이 산점도는 모델이 데이터를 얼마나 잘 학습했는지 평가하는 데 도움을 줍니다.
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
// 데이터 조작 및 머신러닝을 위한 필수 라이브러리 가져오기 import numpy as np from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt // 단계 1: 원시 데이터 준비 // fish_length와 fish_weight는 물고기의 길이와 무게를 나타내는 리스트입니다. // fish_length: 물고기의 길이 (센티미터) // fish_weight: 물고기의 무게 (그램) fish_length = [25.4, 26.3, 26.5, 29.0, 29.0, 30.7, 31.0, ...] fish_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, ...] // 단계 2: 데이터를 하나의 배열로 병합 // np.column_stack 함수는 물고기의 길이와 무게 리스트를 2차원 배열로 병합하는 데 사용됩니다. 여기서 각 행은 하나의 물고기를 나타내며, 열은 길이와 무게를 나타냅니다. fish_data = np.column_stack((fish_length, fish_weight)) // 단계 3: 데이터를 훈련 세트와 테스트 세트로 분할 // train_test_split 함수는 fish_data를 훈련 세트와 테스트 세트로 분할합니다. stratify 매개변수는 훈련 세트와 테스트 세트에 목표 클래스의 비율이 유지되도록 보장합니다. train_input, test_input, train_target, test_target = train_test_split( fish_data, fish_target, stratify=fish_target, random_state=42 ) // 단계 4: 데이터 표준화 // 거리 기반 모델에서는 표준화가 중요합니다. 데이터를 표준화하여 평균을 빼고 표준 편차로 나누어 표준화된 데이터를 얻습니다. mean = np.mean(train_input, axis=0) std = np.std(train_input, axis=0) train_scaled = (train_input - mean) / std test_scaled = (test_input - mean) / std // 단계 5: K-최근접 이웃 모델 학습 // KNeighborsClassifier을 인스턴스화하고 표준화된 훈련 데이터를 바탕으로 모델을 학습시킵니다. KNN 알고리즘은 훈련 데이터에서 가장 가까운 k개의 이웃을 찾아 대다수 클래스를 예측합니다. kn = KNeighborsClassifier() kn.fit(train_scaled, train_target) // 단계 6: 모델 평가 // 모델은 표준화된 테스트 데이터를 바탕으로 평가되며, 그 정확도를 계산하여 출력합니다. accuracy = kn.score(test_scaled, test_target) print("모델 정확도:", accuracy) // 단계 7: 데이터 시각화 // matplotlib을 사용하여 훈련 데이터와 새로운 데이터 포인트(예: 길이 25cm, 무게 150g인 물고기)를 플롯하여 모델의 결정 경계를 시각화합니다. plt.scatter(train_scaled[:, 0], train_scaled[:, 1], label='Train data') plt.scatter(25, 150, marker='^', label='New data') plt.xlabel('길이') plt.ylabel('무게') plt.legend() plt.show() |