Scikit-learn เป็นไลบรารี Machine Learning ฟรีและโอเพนซอร์สที่ได้รับความนิยมมากที่สุดในระบบนิเวศ Python รองรับอัลกอริทึมหลากหลาย เช่น Random Forest, Support Vector Machines, k-Nearest Neighbors และทำงานร่วมกับ NumPy และ SciPy ได้อย่างราบรื่น
ขั้นตอนการสร้างโมเดล
1. การนำเข้าข้อมูล (Data Import)
import pandas as pd url = 'https://example.com/dataset.csv' data = pd.read_csv(url)
2. สำรวจและทำความสะอาดข้อมูล (Data Exploration & Cleaning)
# ดู 5 แถวแรก data.head() # ดู 4 แถวแรก data.head(n=4) # ดู 5 แถวสุดท้าย data.tail() # ดู 4 แถวสุดท้าย data.tail(n=4) # ตรวจสอบข้อมูลขาดหาย data.isnull().sum() # สถิติพื้นฐาน data.describe()
3. การจินตนาการข้อมูล (Data Visualization)
import seaborn as sns import matplotlib.pyplot as plt sns.set(style="whitegrid", color_codes=True) # Count plot ตัวอย่าง sns.countplot(x='Route_To_Market', data=sales_data, hue='Opportunity_Result') plt.show()
4. การเตรียมข้อมูล (Preprocessing)
from sklearn import preprocessing le = preprocessing.LabelEncoder() # แปลงคอลัมน์หมวดหมู่เป็นตัวเลข encoded_values = le.fit_transform(data['column_name']) print(encoded_values) # หรือใช้ OneHotEncoder สำหรับหลายคอลัมน์ from sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder(sparse_output=False) encoded_df = pd.DataFrame(encoder.fit_transform(data[['cat_col1', 'cat_col2']]))
5. การแบ่งข้อมูล Train/Test
from sklearn.model_selection import train_test_split
X = data.drop('target', axis=1)
y = data['target']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
6. การสร้างและฝึกโมเดล (Model Building & Training)
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
# สร้างโมเดล
model = RandomForestClassifier(n_estimators=100, random_state=42)
# ฝึกโมเดล
model.fit(X_train, y_train)
# ทำนาย
y_pred = model.predict(X_test)
# ประเมินผล
print(f"Accuracy: {accuracy_score(y_test, y_pred):.4f}")
print(classification_report(y_test, y_pred))
7. Cross-Validation
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X, y, cv=5)
print(f"CV Scores: {scores}")
print(f"Mean CV Score: {scores.mean():.4f}")
สรุป
Scikit-learn ให้เครื่องมือครบครันสำหรับการสร้างโมเดล Machine Learning ตั้งแต่การเตรียมข้อมูล การเลือกฟีเจอร์ การฝึกโมเดล จนถึงการประเมินผล ทำให้เหมาะสำหรับทั้งผู้เริ่มต้นและผู้เชี่ยวชาญ