1. 程式人生 > >python資料分析練手小專案-汽車銷售偷漏納稅人識別

python資料分析練手小專案-汽車銷售偷漏納稅人識別

本專案主要掌握資料預處理和神經網路、決策樹建模以及利用roc曲線進行模型評價。

import pandas as pd
data=pd.read_excel(data/cardata.xls',index_col=0)

#資料探索
import matplotlib.pyplot as plt
data.describe()

描述

pd.value_counts(data[u'銷售型別'])
pd.value_counts(data[u'銷售模式'])
pd.crosstab(data[u'輸出'],data[u'銷售型別'])
pd.crosstab(data[u'輸出'],data[u'銷售模式'
]) for col in data.columns: if not col in [u'銷售型別',u'銷售模式',u'輸出']: fig = plt.figure() data[col].hist(bins=20, by = data[u'輸出']) fig.show() #資料預處理 data=pd.merge(data,pd.get_dummies(data[u'銷售模式']),left_index=True,right_index=True) data=pd.merge(data,pd.get_dummies(data[u'銷售型別'
]),left_index=True,right_index=True) data['type']=pd.get_dummies(data[u'輸出'])[u'正常'] data = data.iloc[:,3:] del data[u'輸出']
from random import shuffle
data_2=data

data[:5]

看看前幾條

data = data.as_matrix() #將表格轉換為矩陣
shuffle(data)

p = 0.8 #設定訓練資料比例
train = data[:int(len(data)*p),:] #前80%為訓練集
test = data
[int(len(data)*p):,:] #後20%為測試集
#混淆矩陣函式
def cm_plot(y, yp):

  from sklearn.metrics import confusion_matrix

  cm = confusion_matrix(y, yp) 

  import matplotlib.pyplot as plt 
  plt.matshow(cm, cmap=plt.cm.Greens) 
  plt.colorbar() 

  for x in range(len(cm)): 
    for y in range(len(cm)):
      plt.annotate(cm[x,y], xy=(x, y), horizontalalignment='center', verticalalignment='center')

  plt.ylabel('True label') 
  plt.xlabel('Predicted label') 
  return plt


#構建CART決策樹模型
from sklearn.tree import DecisionTreeClassifier #匯入決策樹模型

treefile = 'output/cartree.pkl' #模型輸出名字
tree = DecisionTreeClassifier() #建立決策樹模型
tree.fit(train[:,:25], train[:,25]) #訓練,除了最後一列

#儲存模型
from sklearn.externals import joblib
joblib.dump(tree, treefile)
cm_plot(train[:,25], tree.predict(train[:,:25])).show() #顯示混淆矩陣視覺化結果
#注意到Scikit-Learn使用predict方法直接給出預測結果;
#分類準確率有62+37人

決策樹混淆矩陣

from sklearn.metrics import roc_curve #匯入ROC曲線函式

fpr, tpr, thresholds = roc_curve(test[:,25], tree.predict_proba(test[:,:25])[:,1], pos_label=1)
plt.plot(fpr, tpr, linewidth=2, label = 'ROC of CART', color = 'green') #作出ROC曲線
plt.xlabel('False Positive Rate') #座標軸標籤
plt.ylabel('True Positive Rate') #座標軸標籤
plt.ylim(0,1.05) #邊界範圍
plt.xlim(0,1.05) #邊界範圍
plt.legend(loc=4) #圖例
plt.show() #顯示作圖結果

roc曲線評價模型