Python数据分析与机器学习-交易数据异常检测

源码下载:

http://download.csdn.net/download/adam_zs/10182484



[python]  view plain  copy
  1. ''''' 
  2. 信用卡欺诈检测 
  3. 样本数据极度不均衡: 
  4. 1.过采样 让两个样本的数量同样多 
  5. 2.下采样 让两个样本的数量同样少 
  6. '''  
  7. import numpy as np  
  8. import pandas as pd  
  9. import matplotlib.pyplot as plt  
  10.   
  11. pd.set_option('display.height'1000)  
  12. pd.set_option('display.max_rows'1000)  
  13. pd.set_option('display.max_columns'1000)  
  14. pd.set_option('display.width'1000)  
  15.   
  16. data = pd.read_csv("creditcard.csv")  
  17. # print(data.head())  
  18. ''''' 
  19. Time交易持续时间 
  20. V1-V28 特征属性 
  21. Amount 交易金额 
  22. Class 0正常 1异常 
  23.    Time        V1        V2        V3        V4        V5        V6        V7        V8        V9       V10       V11       V12       V13       V14       V15       V16       V17       V18       V19       V20       V21       V22       V23       V24       V25       V26       V27       V28  Amount  Class 
  24. 0   0.0 -1.359807 -0.072781  2.536347  1.378155 -0.338321  0.462388  0.239599  0.098698  0.363787  0.090794 -0.551600 -0.617801 -0.991390 -0.311169  1.468177 -0.470401  0.207971  0.025791  0.403993  0.251412 -0.018307  0.277838 -0.110474  0.066928  0.128539 -0.189115  0.133558 -0.021053  149.62      0 
  25. 1   0.0  1.191857  0.266151  0.166480  0.448154  0.060018 -0.082361 -0.078803  0.085102 -0.255425 -0.166974  1.612727  1.065235  0.489095 -0.143772  0.635558  0.463917 -0.114805 -0.183361 -0.145783 -0.069083 -0.225775 -0.638672  0.101288 -0.339846  0.167170  0.125895 -0.008983  0.014724    2.69      0 
  26. 2   1.0 -1.358354 -1.340163  1.773209  0.379780 -0.503198  1.800499  0.791461  0.247676 -1.514654  0.207643  0.624501  0.066084  0.717293 -0.165946  2.345865 -2.890083  1.109969 -0.121359 -2.261857  0.524980  0.247998  0.771679  0.909412 -0.689281 -0.327642 -0.139097 -0.055353 -0.059752  378.66      0 
  27. 3   1.0 -0.966272 -0.185226  1.792993 -0.863291 -0.010309  1.247203  0.237609  0.377436 -1.387024 -0.054952 -0.226487  0.178228  0.507757 -0.287924 -0.631418 -1.059647 -0.684093  1.965775 -1.232622 -0.208038 -0.108300  0.005274 -0.190321 -1.175575  0.647376 -0.221929  0.062723  0.061458  123.50      0 
  28. 4   2.0 -1.158233  0.877737  1.548718  0.403034 -0.407193  0.095921  0.592941 -0.270533  0.817739  0.753074 -0.822843  0.538196  1.345852 -1.119670  0.175121 -0.451449 -0.237033 -0.038195  0.803487  0.408542 -0.009431  0.798278 -0.137458  0.141267 -0.206010  0.502292  0.219422  0.215153   69.99      0 
  29. '''  
  30. # help(pd.value_counts)  
  31. count_classes = pd.value_counts(data["Class"])  # 默认按照值排序  
  32. # print(count_classes)  
  33. ''''' 
  34. 0    284315 
  35. 1       492 
  36. '''  
  37. count_classes.plot(kind='bar')  
  38. plt.title("Fraud class histogram")  
  39. plt.xlabel("Class")  
  40. plt.ylabel("Frequency")  
  41. # plt.show()  
  42.   
  43. from sklearn.preprocessing import StandardScaler  
  44.   
  45. # print(type(data['Amount']))  # pandas.core.series.Series  
  46. # print(type(data['Amount'].reshape(-1, 1)))  # numpy.ndarray  
  47.   
  48. # fit_transform转换为一个合适的数据  
  49. data['normAmount'] = StandardScaler().fit_transform(data['Amount'].reshape(-11))  # -1表示行数程序推断,1表示列数  
  50. # print(help(data.drop))  
  51. data.drop(['Time''Amount'], axis=1)  
  52. # print(data.head())  
  53.   
  54. X = data.ix[:, data.columns != 'Class']  
  55. y = data.ix[:, data.columns == 'Class']  
  56.   
  57. '''''下采样'''  
  58.   
  59. # Number of data points in the minority class  
  60. fraud_indices = np.array(data[data['Class'] == 1].index)  # 异常样本索引  
  61. normal_indices = np.array(data[data['Class'] == 0].index)  # 正常样本索引  
  62.   
  63. # choice(选择源,选择数量,replace:true采样结果有重复,false采样结果没有重复)  
  64. random_normal_indices = np.random.choice(normal_indices, len(fraud_indices), replace=False)  
  65.   
  66. # 把两个样本合并  
  67. under_sample_indices = np.concatenate([fraud_indices, random_normal_indices])  
  68.   
  69. #  下采样之后的数据 iloc根据索引位置取值  
  70. under_sample_data = data.iloc[under_sample_indices, :]  
  71.   
  72. X_undersample = under_sample_data.ix[:, under_sample_data.columns != 'Class']  
  73. y_undersample = under_sample_data.ix[:, under_sample_data.columns == 'Class']  
  74.   
  75. # print("Percentage of normal transactions: ",  
  76. #       len(under_sample_data[under_sample_data.Class == 0]) / len(under_sample_data))  
  77. # print("Percentage of fraud transactions: ",  
  78. #       len(under_sample_data[under_sample_data.Class == 1]) / len(under_sample_data))  
  79. # print("Total number of transactions in resampled data: ", len(under_sample_data))  
  80.   
  81.   
  82. from sklearn.cross_validation import train_test_split  
  83.   
  84. # cross_validation 交叉验证模块  
  85. # test_size:测试集占30%,random_state=0 每次随机切分的结果一样  
  86. # 原始全部的数据集  
  87. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)  
  88.   
  89. print("Number transactions train dataset: ", len(X_train))  
  90. print("Number transactions test dataset: ", len(X_test))  
  91. print("Total number of transactions: ", len(X_train) + len(X_test))  
  92.   
  93. # 下采样数据集  
  94. X_train_undersample, X_test_undersample, y_train_undersample, y_test_undersample = train_test_split(X_undersample  
  95.                                                                                                     , y_undersample  
  96.                                                                                                     , test_size=0.3  
  97.                                                                                                     , random_state=0)  
  98. print("")  
  99. print("Number transactions train dataset: ", len(X_train_undersample))  
  100. print("Number transactions test dataset: ", len(X_test_undersample))  
  101. print("Total number of transactions: ", len(X_train_undersample) + len(X_test_undersample))  
  102.   
  103. from sklearn.linear_model import LogisticRegression  # LogisticRegression逻辑回归  
  104. from sklearn.cross_validation import KFold, cross_val_score  # KFold模型建立做几倍的交叉验证 cross_val_score交叉验证评估结果  
  105. from sklearn.metrics import confusion_matrix, recall_score, classification_report  # confusion_matrix混淆矩阵  
  106.   
  107.   
  108. def printing_Kfold_scores(x_train_data, y_train_data):  
  109.     fold = KFold(len(y_train_data), 5, shuffle=False)  # 把原始训练集切分为5份  
  110.   
  111.     # Different C parameters  
  112.     c_param_range = [0.010.1110100]  # 正则化惩罚项  
  113.   
  114.     results_table = pd.DataFrame(index=range(len(c_param_range), 2), columns=['C_parameter''Mean recall score'])  
  115.     results_table['C_parameter'] = c_param_range  
  116.   
  117.     # the k-fold will give 2 lists: train_indices = indices[0], test_indices = indices[1]  
  118.     j = 0  
  119.     for c_param in c_param_range:  # 找最好的C参数  
  120.         print('-------------------------------------------')  
  121.         print('C parameter: ', c_param)  
  122.         print('-------------------------------------------')  
  123.         print('')  
  124.   
  125.         recall_accs = []  
  126.         for iteration, indices in enumerate(fold, start=1):  # 进行交叉验证  
  127.   
  128.             # Call the logistic regression model with a certain C parameter  
  129.             lr = LogisticRegression(C=c_param, penalty='l1')  
  130.   
  131.             # Use the training data to fit the model. In this case, we use the portion of the fold to train the model  
  132.             # with indices[0]. We then predict on the portion assigned as the 'test cross validation' with indices[1]  
  133.             lr.fit(x_train_data.iloc[indices[0], :], y_train_data.iloc[indices[0], :].values.ravel())  
  134.   
  135.             # Predict values using the test indices in the training data  
  136.             y_pred_undersample = lr.predict(x_train_data.iloc[indices[1], :].values)  
  137.   
  138.             # Calculate the recall score and append it to a list for recall scores representing the current c_parameter  
  139.             recall_acc = recall_score(y_train_data.iloc[indices[1], :].values, y_pred_undersample)  # 计算召回率  
  140.             recall_accs.append(recall_acc)  
  141.             print('Iteration ', iteration, ': recall score = ', recall_acc)  
  142.   
  143.         # The mean value of those recall scores is the metric we want to save and get hold of.  
  144.         results_table.ix[j, 'Mean recall score'] = np.mean(recall_accs)  
  145.         j += 1  
  146.         print('')  
  147.         print('Mean recall score ', np.mean(recall_accs))  
  148.         print('')  
  149.   
  150.     best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter']  
  151.   
  152.     # Finally, we can check which C parameter is the best amongst the chosen.  
  153.     print('*********************************************************************************')  
  154.     print('Best model to choose from cross validation is with C parameter = ', best_c)  
  155.     print('*********************************************************************************')  
  156.   
  157.     return best_c  
  158.   
  159.   
  160. best_c = printing_Kfold_scores(X_train_undersample, y_train_undersample)  
  161.   
  162. import itertools  
  163.   
  164.   
  165. def plot_confusion_matrix(cm, classes,  
  166.                           title='Confusion matrix',  
  167.                           cmap=plt.cm.Blues):  
  168.     """ 
  169.     This function prints and plots the confusion matrix. 
  170.     """  
  171.     plt.imshow(cm, interpolation='nearest', cmap=cmap)  
  172.     plt.title(title)  
  173.     plt.colorbar()  
  174.     tick_marks = np.arange(len(classes))  
  175.     plt.xticks(tick_marks, classes, rotation=0)  
  176.     plt.yticks(tick_marks, classes)  
  177.   
  178.     thresh = cm.max() / 2.  
  179.     for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):  
  180.         plt.text(j, i, cm[i, j],  
  181.                  horizontalalignment="center",  
  182.                  color="white" if cm[i, j] > thresh else "black")  
  183.   
  184.     plt.tight_layout()  
  185.     plt.ylabel('True label')  
  186.     plt.xlabel('Predicted label')  
  187.   
  188.   
  189. lr = LogisticRegression(C=best_c, penalty='l1')  
  190. lr.fit(X_train_undersample, y_train_undersample.values.ravel())  
  191. y_pred_undersample = lr.predict(X_test_undersample.values)  
  192.   
  193. # Compute confusion matrix  
  194. cnf_matrix = confusion_matrix(y_test_undersample, y_pred_undersample)  
  195. np.set_printoptions(precision=2)  
  196.   
  197. print("Recall metric in the testing dataset: ", cnf_matrix[11] / (cnf_matrix[10] + cnf_matrix[11]))  
  198.   
  199. # Plot non-normalized confusion matrix  
  200. class_names = [01]  
  201. plt.figure()  
  202. plot_confusion_matrix(cnf_matrix  
  203.                       , classes=class_names  
  204.                       , title='Confusion matrix')  
  205. plt.show()  
  206.   
  207. lr = LogisticRegression(C=best_c, penalty='l1')  
  208. lr.fit(X_train_undersample, y_train_undersample.values.ravel())  
  209. y_pred = lr.predict(X_test.values)  
  210.   
  211. # Compute confusion matrix  
  212. cnf_matrix = confusion_matrix(y_test, y_pred)  
  213. np.set_printoptions(precision=2)  
  214.   
  215. print("Recall metric in the testing dataset: ", cnf_matrix[11] / (cnf_matrix[10] + cnf_matrix[11]))  
  216.   
  217. # Plot non-normalized confusion matrix  
  218. class_names = [01]  
  219. plt.figure()  
  220. plot_confusion_matrix(cnf_matrix  
  221.                       , classes=class_names  
  222.                       , title='Confusion matrix')  
  223. plt.show()  
  224.   
  225. lr = LogisticRegression(C=best_c, penalty='l1')  
  226. lr.fit(X_train_undersample, y_train_undersample.values.ravel())  
  227. y_pred = lr.predict(X_test.values)  
  228.   
  229. # Compute confusion matrix  
  230. cnf_matrix = confusion_matrix(y_test, y_pred)  
  231. np.set_printoptions(precision=2)  
  232.   
  233. print("Recall metric in the testing dataset: ", cnf_matrix[11] / (cnf_matrix[10] + cnf_matrix[11]))  
  234.   
  235. # Plot non-normalized confusion matrix  
  236. class_names = [01]  
  237. plt.figure()  
  238. plot_confusion_matrix(cnf_matrix  
  239.                       , classes=class_names  
  240.                       , title='Confusion matrix')  
  241. plt.show()  
  242.   
  243. # 拿到数据不处理就开始给机器学习  
  244. best_c = printing_Kfold_scores(X_train, y_train)  
  245.   
  246. lr = LogisticRegression(C=best_c, penalty='l1')  
  247. lr.fit(X_train, y_train.values.ravel())  
  248. y_pred_undersample = lr.predict(X_test.values)  
  249.   
  250. # Compute confusion matrix  
  251. cnf_matrix = confusion_matrix(y_test, y_pred_undersample)  
  252. np.set_printoptions(precision=2)  
  253.   
  254. print("Recall metric in the testing dataset: ", cnf_matrix[11] / (cnf_matrix[10] + cnf_matrix[11]))  
  255.   
  256. # Plot non-normalized confusion matrix  
  257. class_names = [01]  
  258. plt.figure()  
  259. plot_confusion_matrix(cnf_matrix  
  260.                       , classes=class_names  
  261.                       , title='Confusion matrix')  
  262. plt.show()  
  263.   
  264. lr = LogisticRegression(C=0.01, penalty='l1')  
  265. lr.fit(X_train_undersample, y_train_undersample.values.ravel())  
  266. y_pred_undersample_proba = lr.predict_proba(X_test_undersample.values)  # predict_proba预测概率值  
  267.   
  268. thresholds = [0.10.20.30.40.50.60.70.80.9]  # 阈值 大于这个值的认为是True  
  269.   
  270. plt.figure(figsize=(1010))  
  271.   
  272. j = 1  
  273. for i in thresholds:  
  274.     y_test_predictions_high_recall = y_pred_undersample_proba[:, 1] > i  
  275.   
  276.     plt.subplot(33, j)  
  277.     j += 1  
  278.   
  279.     # Compute confusion matrix  
  280.     cnf_matrix = confusion_matrix(y_test_undersample, y_test_predictions_high_recall)  
  281.     np.set_printoptions(precision=2)  
  282.   
  283.     print("Recall metric in the testing dataset: ", cnf_matrix[11] / (cnf_matrix[10] + cnf_matrix[11]))  
  284.   
  285.     # Plot non-normalized confusion matrix  
  286.     class_names = [01]  
  287.     plot_confusion_matrix(cnf_matrix  
  288.                           , classes=class_names  
  289.                           , title='Threshold >= %s' % i)  
  290.   
  291. '''''过采样'''  
  292. import pandas as pd  
  293. from imblearn.over_sampling import SMOTE  # imblearn不平衡数据模块  
  294. from sklearn.metrics import confusion_matrix  
  295.   
  296. credit_cards = pd.read_csv('creditcard.csv')  
  297.   
  298. columns = credit_cards.columns  
  299. # The labels are in the last column ('Class'). Simply remove it to obtain features columns  
  300. features_columns = columns.delete(len(columns) - 1)  
  301.   
  302. features = credit_cards[features_columns]  
  303. labels = credit_cards['Class']  
  304.   
  305. features_train, features_test, labels_train, labels_test = train_test_split(features,  
  306.                                                                             labels,  
  307.                                                                             test_size=0.2,  
  308.                                                                             random_state=0)  
  309.   
  310. oversampler = SMOTE(random_state=0)  # 用SMOTE算法生成数据,random_state=0每次生成的数据都是一样的  
  311. os_features, os_labels = oversampler.fit_sample(features_train, labels_train)  # 只对训练集生成数据,测试集不用生成数据  
  312.   
  313. len(os_labels[os_labels == 1])  
  314. os_features = pd.DataFrame(os_features)  
  315. os_labels = pd.DataFrame(os_labels)  
  316. best_c = printing_Kfold_scores(os_features, os_labels)  
  317.   
  318. lr = LogisticRegression(C=best_c, penalty='l1')  
  319. lr.fit(os_features, os_labels.values.ravel())  
  320. y_pred = lr.predict(features_test.values)  
  321.   
  322. # Compute confusion matrix  
  323. cnf_matrix = confusion_matrix(labels_test, y_pred)  
  324. np.set_printoptions(precision=2)  
  325.   
  326. print("Recall metric in the testing dataset: ", cnf_matrix[11] / (cnf_matrix[10] + cnf_matrix[11]))  
  327.   
  328. # Plot non-normalized confusion matrix  
  329. class_names = [01]  
  330. plt.figure()  
  331. plot_confusion_matrix(cnf_matrix  
  332.                       , classes=class_names  
  333.                       , title='Confusion matrix')  
  334. plt.show()  
  335.   
  336. ''''' 
  337. 样本数据不均衡,优先采用过采样 
  338. '''  


个人分类:  python
腰椎疼痛不止?只需一招就解决!青青 · 顶新
能看5万米的手机望远镜今日特价!仅限沈阳!同勉商贸 · 顶新
用Python做单变量数据集的异常点分析数据

2017年03月21日 3.59MB 下载

个人资料

原创
267
粉丝
117
喜欢
393
评论
257
等级:
访问:
33万+
积分:
6656
排名:
4593
勋章:
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值