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

ทำนาย Customer Churn ด้วย Machine Learning ใน Python

ใช้ Logistic Regression ทำนายลูกค้าที่จะเลิกใช้บริการ (Churn) จากข้อมูล Telecom

ขั้นตอนหลัก

  1. Data Loading: โหลด CSV ด้วย pandas
  2. EDA: ดูสัดส่วน Churn, dropping คอลัมน์ไม่เกี่ยวข้อง (customerID)
  3. Preprocessing: Label Encoding ทุกคอลัมน์ categorical
  4. Train/Test Split: 80/20
  5. Model Training: LogisticRegression
  6. Evaluation: Accuracy, Confusion Matrix, Feature Weights

โค้ดสำคัญ

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn import preprocessing

# Load
df = pd.read_csv('Telecom_customers.csv')
df.drop(['customerID'], axis=1, inplace=True)
df.pop('TotalCharges')

# Label Encoding
le = preprocessing.LabelEncoder()
for col in df.columns:
    if df[col].dtype == 'object':
        df[col] = le.fit_transform(df[col])

# Split
X = df.drop('Churn', axis=1)
y = df['Churn'].astype(int)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

# Evaluate
acc = metrics.accuracy_score(y_test, y_pred) * 100
cm = confusion_matrix(y_test, y_pred)
print(f"Accuracy: {acc:.2f}%")
print(f"Confusion Matrix:\n{cm}")

# Feature weights
weights = pd.Series(model.coef_[0], index=X.columns).sort_values(ascending=False)
print("Feature Weights:")
print(weights)

ผลลัพธ์ตัวอย่าง

Accuracy: 80.84%
Confusion Matrix:
[[928 109]
 [161 211]]

Feature Weights:
PaperlessBilling      0.389
SeniorCitizen         0.247
InternetService       0.209
...
Contract             -0.730
PhoneService         -0.951

สรุป

Logistic Regression ให้ baseline ดี สามารถอธิบาย feature importance ได้ ต่อไปอาจลอง Random Forest หรือ XGBoost