Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การ Preprocess ข้อมูลด้วย scikit-learn ใน Python: ตัวอย่าง Binarizer

Data Preprocessing เป็นขั้นตอนสำคัญใน ML Pipeline: ทำความสะอาดข้อมูล ลบ Noise จัดการ Missing Values แปลงข้อมูลให้เหมาะสมกับอัลกอริทึม

scikit-learn มีโมดูล sklearn.preprocessing สำหรับ Preprocessing หลากหลาย เช่น Scaling, Encoding, Imputation, Discretization, Binarization

ตัวอย่าง: Binarizer - แปลงตัวเลขเป็น Boolean (0/1)


import numpy as np
from sklearn import preprocessing

input_data = np.array([
    [34.78, 31.9, -65.5],
    [-16.5, 2.45, -83.5],
    [0.5, -87.98, 45.62],
    [5.9, 2.38, -55.82]
])

# Threshold = 0.5: ค่า > 0.5 → 1, ค่า ≤ 0.5 → 0
data_binarized = preprocessing.Binarizer(threshold=0.5).transform(input_data)

print("Values converted from numeric to Boolean :\n", data_binarized)

ผลลัพธ์


Values converted from numeric to Boolean :
[[1. 1. 0.]
 [0. 1. 0.]
 [0. 0. 1.]
 [1. 1. 0.]]

คำอธิบาย

  • นำเข้า NumPy และ sklearn.preprocessing

  • สร้างข้อมูลตัวอย่าง 4x3

  • ใช้ Binarizer(threshold=0.5) แปลงค่า > 0.5 เป็น 1.0, ≤ 0.5 เป็น 0.0

  • เรียก .transform() เพื่อแปลงข้อมูล

Preprocessing Tools หลักใน sklearn.preprocessing

Class/Functionวัตถุประสงค์
StandardScalerStandardization (Mean=0, Std=1)
MinMaxScalerNormalization ไปยัง [0,1]
RobustScalerScaling ทนต่อ Outliers (ใช้ Median/IQR)
MaxAbsScalerScaling ด้วย Max Absolute Value
Binarizerแปลงเป็น 0/1 ตาม Threshold
OneHotEncoderCategorical → One-Hot Vectors
LabelEncoderCategorical Labels → Integers
OrdinalEncoderOrdinal Categorical → Integers
SimpleImputer填补 Missing Values (mean, median, mode)
KBinsDiscretizerContinuous → Discrete Bins
PolynomialFeaturesสร้าง Polynomial Features

Best Practice: ใช้ Pipeline


from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('clf', LogisticRegression())
])
pipe.fit(X_train, y_train)

Pipeline ป้องกัน Data Leakage และทำให้ Workflow สะอาด ต่อเนื่อง