此專案示範如何使用決策樹分類器來預測客戶流失(客戶是否離開服務)。此資料集包括年齡、每月費用和客戶服務電話等特徵,目的是預測客戶是否會流失。
模型使用 Scikit-learn 的決策樹分類器進行訓練,程式碼將決策樹視覺化,以便更好地理解模型如何做出決策。
import pandas as pd import matplotlib.pyplot as plt import warnings from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score from sklearn import tree
熊貓(pd):
Matplotlib(plt):
警告(警告):
Scikit-learn 庫:
import pandas as pd import matplotlib.pyplot as plt import warnings from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score from sklearn import tree
warnings.filterwarnings("ignore")
在這裡,我們為此專案建立一個合成資料集。該資料集模擬了一家電信公司的客戶訊息,具有年齡、月費、CustomerServiceCalls 和目標變數流失(客戶是否流失)等特徵。
Pandas DataFrame:資料被建構為 DataFrame (df),一種二維標記資料結構,允許輕鬆操作和分析資料。
import pandas as pd import matplotlib.pyplot as plt import warnings from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score from sklearn import tree
warnings.filterwarnings("ignore")
data = { 'CustomerID': range(1, 101), # Unique ID for each customer 'Age': [20, 25, 30, 35, 40, 45, 50, 55, 60, 65]*10, # Age of customers 'MonthlyCharge': [50, 60, 70, 80, 90, 100, 110, 120, 130, 140]*10, # Monthly bill amount 'CustomerServiceCalls': [1, 2, 3, 4, 0, 1, 2, 3, 4, 0]*10, # Number of customer service calls 'Churn': ['No', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'No', 'Yes']*10 # Churn status } df = pd.DataFrame(data) print(df.head())
X = df[['Age', 'MonthlyCharge', 'CustomerServiceCalls']] # Features y = df['Churn'] # Target Variable
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
clf = DecisionTreeClassifier() clf.fit(X_train, y_train)
import pandas as pd import matplotlib.pyplot as plt import warnings from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score from sklearn import tree
以上是預測客戶流失的決策樹分類器範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!