Scikit-learn (sklearn) เป็นไลบรารี Python สำหรับ Machine Learning ที่ทรงพลังและมั่นคง มีเครื่องมือหลากหลายสำหรับการสร้างแบบจำลองทางสถิติ ได้แก่ Classification, Regression, Clustering, Dimensionality Reduction และอื่นๆ สร้างบน NumPy, SciPy และ Matplotlib
ก่อนนำข้อมูลไปฝึกโมเดล Machine Learning จำเป็นต้องแบ่งข้อมูลออกเป็น 2 ชุด:
- Training Set: ใช้ฝึกโมเดล ให้โมเดลเรียนรูปแบบจากข้อมูล
- Test Set: ไม่ได้ใช้ในการฝึก ใช้ประเมินประสิทธิภาพโมเดลกับข้อมูลที่ไม่เคยเห็น เพื่อตรวจสอบความสามารถในการ generalize
หลังปรับ Hyperparameters และน้ำหนัก (Weights) ให้เหมาะสมแล้ว จึงนำ Test Set มาวัดประสิทธิภาพจริงของโมเดล
ตัวอย่างโค้ด
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
my_data = load_iris()
X = my_data.data
y = my_data.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=2
)
print("The dimensions of the features of training data")
print(X_train.shape)
print("The dimensions of the features of test data")
print(X_test.shape)
print("The dimensions of the target values of training data")
print(y_train.shape)
print("The dimensions of the target values of test data")
print(y_test.shape)
ผลลัพธ์
The dimensions of the features of training data (120, 4)
The dimensions of the features of test data (30, 4)
The dimensions of the target values of training data (120,)
The dimensions of the target values of test data (30,)
คำอธิบาย
นำเข้าโมดูล
load_irisและtrain_test_splitโหลดชุดข้อมูล Iris (150 ตัวอย่าง, 4 ฟีเจอร์, 3 คลาส)
แยก Features (X) และ Target (y)
แบ่งข้อมูลด้วย
train_test_splitอัตราส่วน 80:20 (test_size=0.2) และกำหนด random_state เพื่อให้ผลลัพธ์ซ้ำได้แสดงมิติของชุดข้อมูล Train และ Test
หมายเหตุ: พารามิเตอร์ stratify=y สามารถเพิ่มได้เพื่อรักษาสัดส่วนคลาสในแต่ละชุด (Stratified Sampling) ซึ่งสำคัญเมื่อข้อมูลไม่สมดุล (Imbalanced Data)