Python数据分析与机器学习-用户流失预警

  1. import pandas as pd  
  2. import numpy as np  
  3.   
  4. pd.set_option('display.height'9999)  
  5. pd.set_option('display.max_rows'9999)  
  6. pd.set_option('display.max_columns'9999)  
  7. pd.set_option('display.width'9999)  
  8.   
  9. churn_df = pd.read_csv('churn.csv')  
  10. ''''' 
  11.   State  Account Length  Area Code     Phone Int'l Plan VMail Plan  VMail Message  Day Mins  Day Calls  Day Charge  Eve Mins  Eve Calls  Eve Charge  Night Mins  Night Calls  Night Charge  Intl Mins  Intl Calls  Intl Charge  CustServ Calls  Churn? 
  12. 0    KS             128        415  382-4657         no        yes             25     265.1        110       45.07     197.4         99       16.78       244.7           91         11.01       10.0           3         2.70               1  False. 
  13. 1    OH             107        415  371-7191         no        yes             26     161.6        123       27.47     195.5        103       16.62       254.4          103         11.45       13.7           3         3.70               1  False. 
  14. 2    NJ             137        415  358-1921         no         no              0     243.4        114       41.38     121.2        110       10.30       162.6          104          7.32       12.2           5         3.29               0  False. 
  15. 3    OH              84        408  375-9999        yes         no              0     299.4         71       50.90      61.9         88        5.26       196.9           89          8.86        6.6           7         1.78               2  False. 
  16. 4    OK              75        415  330-6626        yes         no              0     166.7        113       28.34     148.3        122       12.61       186.9          121          8.41       10.1           3         2.73               3  False. 
  17.  
  18. '''  
  19. churn_feat_space = churn_df.drop(['State''Area Code''Phone''Churn?'], axis=1)  
  20. yes_no_cols = ["Int'l Plan""VMail Plan"]  
  21. churn_feat_space[yes_no_cols] = churn_feat_space[yes_no_cols] == 'yes'  
  22. # features = churn_feat_space.columns  
  23. # print(churn_feat_space.head())  
  24. ''''' 
  25.    Account Length  Int'l Plan  VMail Plan  VMail Message  Day Mins  Day Calls  Day Charge  Eve Mins  Eve Calls  Eve Charge  Night Mins  Night Calls  Night Charge  Intl Mins  Intl Calls  Intl Charge  CustServ Calls 
  26. 0             128       False        True             25     265.1        110       45.07     197.4         99       16.78       244.7           91         11.01       10.0           3         2.70               1 
  27. 1             107       False        True             26     161.6        123       27.47     195.5        103       16.62       254.4          103         11.45       13.7           3         3.70               1 
  28. 2             137       False       False              0     243.4        114       41.38     121.2        110       10.30       162.6          104          7.32       12.2           5         3.29               0 
  29. 3              84        True       False              0     299.4         71       50.90      61.9         88        5.26       196.9           89          8.86        6.6           7         1.78               2 
  30. 4              75        True       False              0     166.7        113       28.34     148.3        122       12.61       186.9          121          8.41       10.1           3         2.73               3 
  31. '''  
  32. X = churn_feat_space.as_matrix().astype(np.float)  
  33. churn_result = churn_df['Churn?']  
  34. y = np.where(churn_result == 'True.'10)  
  35.   
  36. from sklearn.preprocessing import StandardScaler  
  37.   
  38. scaler = StandardScaler()  
  39. X = scaler.fit_transform(X)  
  40. # print(X[0])  
  41. ''''' 
  42. [ 0.67648946 -0.32758048  1.6170861   1.23488274  1.56676695  0.47664315 
  43.   1.56703625 -0.07060962 -0.05594035 -0.07042665  0.86674322 -0.46549436 
  44.   0.86602851 -0.08500823 -0.60119509 -0.0856905  -0.42793202] 
  45. '''  
  46.   
  47. '''''交叉验证通用函数'''  
  48. from sklearn.cross_validation import KFold  
  49.   
  50.   
  51. # X,y,选择的分类器,参数  
  52. def run_cv(X, y, clf_class, **kwargs):  
  53.     # Construct a kfolds object  
  54.     kf = KFold(len(y), n_folds=5, shuffle=True)  
  55.     y_pred = y.copy()  
  56.   
  57.     # Iterate through folds  
  58.     for train_index, test_index in kf:  
  59.         X_train, X_test = X[train_index], X[test_index]  
  60.         y_train = y[train_index]  
  61.         # Initialize a classifier with key word arguments  
  62.         clf = clf_class(**kwargs)  
  63.         clf.fit(X_train, y_train)  
  64.         y_pred[test_index] = clf.predict(X_test)  
  65.     return y_pred  
  66.   
  67.   
  68. from sklearn.svm import SVC  
  69. from sklearn.ensemble import RandomForestClassifier as RF  
  70. from sklearn.neighbors import KNeighborsClassifier as KNN  
  71.   
  72.   
  73. # 精度  
  74. def accuracy(y_true, y_pred):  
  75.     # NumPy interprets True and False as 1. and 0.  
  76.     return np.mean(y_true == y_pred)  
  77.   
  78.   
  79. print("Support vector machines:")  
  80. print("%.3f" % accuracy(y, run_cv(X, y, SVC)))  
  81. print("Random forest:")  
  82. print("%.3f" % accuracy(y, run_cv(X, y, RF)))  
  83. print("K-nearest-neighbors:")  
  84. print("%.3f" % accuracy(y, run_cv(X, y, KNN)))  
  85.   
  86.   
  87. # 客户流失的概率  
  88. def run_prob_cv(X, y, clf_class, **kwargs):  
  89.     kf = KFold(len(y), n_folds=5, shuffle=True)  
  90.     y_prob = np.zeros((len(y), 2))  
  91.     for train_index, test_index in kf:  
  92.         X_train, X_test = X[train_index], X[test_index]  
  93.         y_train = y[train_index]  
  94.         clf = clf_class(**kwargs)  
  95.         clf.fit(X_train, y_train)  
  96.         # Predict probabilities, not classes  
  97.         y_prob[test_index] = clf.predict_proba(X_test)  
  98.     return y_prob  
  99.   
  100.   
  101. # Use 10 estimators so predictions are all multiples of 0.1  
  102. pred_prob = run_prob_cv(X, y, RF, n_estimators=10)  
  103. # print pred_prob[0]  
  104. pred_churn = pred_prob[:, 1]  
  105. is_churn = y == 1  
  106.   
  107. # Number of times a predicted probability is assigned to an observation  
  108. counts = pd.value_counts(pred_churn)  
  109. # print counts  
  110.   
  111. # calculate true probabilities  
  112. true_prob = {}  
  113. for prob in counts.index:  
  114.     true_prob[prob] = np.mean(is_churn[pred_churn == prob])  
  115.     true_prob = pd.Series(true_prob)  
  116.   
  117. # pandas-fu  
  118. counts = pd.concat([counts, true_prob], axis=1).reset_index()  
  119. counts.columns = ['pred_prob''count''true_prob']  
  120. print(counts)  

你可能感兴趣的:(PYTHON)