機器學習筆記《四》:線性迴歸,邏輯迴歸案例與重點細節問題分析
阿新 • • 發佈:2018-12-12
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
path = "data"+os.sep+"creditcard.csv";
pdData = pd.read_csv(path);
pdData.head(4)
#Class 這一列表示的是 0 為正常 1為有問題,先來看看 0,1的分佈情況 class_count = pdData.Class.value_counts(sort=True) #value_counts() 以Series形式返回指定列的不同取值的頻率 #另外一種呼叫方法: pd.value_counts(pdData['Class'],sort=True) class_count
#畫出來 可以發現數據超極不均衡 , 0的樣例遠遠大於1的樣例,解決方法有 下采樣和過取樣
class_count.plot(kind='bar')
plt.show()
#對資料的值之間差距太大的Amount列進行標準化,縮小差距,但不影響排名 from sklearn import preprocessing as pp #values: 以array形式返回指定column的所有取值 pdData['normAmount'] = pp.StandardScaler().fit_transform(pdData['Amount'].values.reshape(-1,1)) # pdData['Amount'].shape (284807,) # pdData['Amount'].reshape(-1,1).shape (284807, 1) # pdData['Amount'].values.reshape(-1,1).shape (284807, 1) print(pdData['Amount'].head()) print("標準化後的資料:") print(pdData['normAmount'].head()) #刪掉已經沒有用的兩列資料 pdData = pdData.drop(['Time','Amount'],axis = 1) #1表示列,0表示行
#分離 資料 和 結果 進行下采樣 X = pdData.loc[:,pdData.columns != "Class"] y = pdData.loc[:,pdData.columns == "Class"] #對資料進行下采樣 number_record_fraud = len(pdData[pdData.Class == 1]) #class = 1 的數目 492 fraud_indices = np.array(pdData[pdData.Class == 1].index) #class = 1 的樣例 索引 normal_indices = pdData[pdData.Class == 0].index #class = 0 的樣例 索引 #從正常(class=0)中隨機選出和欺詐樣例相同的樣例 random_normal_indices =np.array( np.random.choice(normal_indices,number_record_fraud,replace=False)) #將 ‘隨機正常’和 ‘欺詐’ 的索引拼起來並找到兩者的資料 # under_sample_indicis = np.concatenate([random_normal_indices,fraud_indices]) #np.concatenate([np.array([1,2,3]),np.array([4,5,6])]) array([1, 2, 3, 4, 5, 6]) under_sample_data = pdData.loc[under_sample_indicis] #下采樣後的資料和結果 X_undersample = under_sample_data.loc[:,under_sample_data.columns!='Class'] y_undersample = under_sample_data.loc[:,under_sample_data.columns =='Class'] # Showing ratio print("Percentage of normal transactions正常人比例: ", len(under_sample_data[under_sample_data.Class == 0])/len(under_sample_data)) print("Percentage of fraud transactions欺詐者比例: ", len(under_sample_data[under_sample_data.Class == 1])/len(under_sample_data)) print("Total number of transactions in resampled data總資料: ", len(under_sample_data))
#交叉驗證
#一般會對資料集進行切分,比如80%作為訓練集,20%作為測試集
#交叉驗證是對80%的訓練集 進行均分為3份,兩份為一個單位進行訓練,剩下的一份做測試
#這是求穩的做法
from sklearn import cross_validation as cv
#切分 訓練集和測試集
#random_state不加這個引數每次的劃分都是不一樣的,加上後無論值等於幾都保證是一樣的
#全部資料的訓練集
X_train, X_test, y_train, y_test =cv.train_test_split(X, y ,test_size=0.3,random_state=0)
len(X_train) #199364
#下采樣資料的訓練集
X_train_undersample, X_test_undersample, y_train_undersample, y_test_undersample =cv.train_test_split(X_undersample, y_undersample ,test_size=0.3,random_state=0)
len(X_train_undersample) #688
#開始建立模型分析
#對預測結果精度分析判斷是否是預測正確是很不靠譜對,如1000中有10個正例,10個都沒判斷出來也是0.999
#使用: recall = Tp/(Tp+Fp) 混淆矩陣
#Tp : 正例猜成正例 Fp:正例猜成負例
#TN : 負例猜成負例 FN: 負例猜成正例
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import KFold,cross_val_score
from sklearn.metrics import confusion_matrix,recall_score,classification_report
#過擬合: 在訓練集中表現很好,測試集上表現糟糕
#過多的變數(特徵),同時只有非常少的訓練資料,會導致出現過度擬合的問題
#https://www.cnblogs.com/jianxinzhou/p/4083921.html
#https://blog.csdn.net/winycg/article/details/80313123
def printing_Kfold_scores(X_train_data,y_train_data):
#KFold交叉驗證 把 X_train_data 分成5份 每次拿4份train 1份test
fold = KFold(len(X_train_data),5,shuffle=False);
#正則化懲罰
#懲罰係數
c_param_range = [0.01,0.1,1,10,100]
results_table = pd.DataFrame(index = range(len(c_param_range),2), columns = ['C_parameter','Mean recall score'])
results_table['C_parameter'] = c_param_range
#對每個懲罰係數進行迴圈
j=0
for c_param in c_param_range:
print("----------------")
print('C param:',c_param)
print("----------------")
recall_accs=[] #存放recall值
# for train,test in fold 每次便利fold可以拿到一個訓練集索引,一個測試集索引,但是這裡不這麼取
for iteration,indices in enumerate(fold,start=1): #in enumerate(x) 可以同時拿到索引,start=1表示索引從1開始
#iteration表示索引 indices[0]是訓練集的索引 indices[1]是測試集的索引
#用確定的懲罰係數構造邏輯迴歸 #L2 = landa/2m * w^2
lr = LogisticRegression(C=c_param,penalty = 'l1') #使用L1正則化 landa/2m * sum|w|
# 使用訓練集資料indices[0]修正模型
# 用測試集 indices[1] 預測
#放入 資料 和 結果 讓它自己訓練
lr.fit(X_train_data.iloc[indices[0],:],y_train_data.iloc[indices[0],:].values.ravel())
#用測試集 測試
y_pred_undersample = lr.predict(X_train_data.iloc[indices[1],:].values)
#計算recall值 ,並加到陣列中
recall_acc = recall_score(y_train_data.iloc[indices[1],:].values,y_pred_undersample) #recall_score(真實結果,預測結果)
recall_accs.append(recall_acc)
print('Iteration ', iteration,': recall score = ', recall_acc)
# 計算得到 這一個 懲罰引數 下每一組訓練集測試集的平均值
results_table.ix[j,'Mean recall score'] = np.mean(recall_accs)
j += 1
print('')
print('Mean recall score ', np.mean(recall_accs))
print('')
#根據所有懲罰係數得到recall判斷最好的懲罰係數
best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter']
# Finally, we can check which C parameter is the best amongst the chosen.
print('*********************************************************************************')
print('Best model to choose from cross validation is with C parameter = ', best_c)
print('*********************************************************************************')
return best_c
#使用下采樣的資料進行測試
best_c = printing_Kfold_scores(X_train_undersample,y_train_undersample)
#畫混淆矩陣
#引數 1.函式confusion_matrix(真實值,預測值)得到的混淆矩陣,這個函式得到的其實已經是結果了,這裡只是將結果畫出來
# 2.classes 值的集合 3.title 圖名 4.
def plot_confusion_matrix(cm,classes,title='Confusion matrix',cmap=plt.cm.Blues):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar() #影象右側的漸變色條
tick_marks = np.arange(len(classes)) # 座標軸上的數值個數進行劃分
plt.xticks(tick_marks, classes, rotation=0)
plt.yticks(tick_marks, classes)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
#超過 最大值半數 色塊上的文字用 white 否則 black
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout() # 會自動調整子圖引數,使之填充整個影象區域
plt.ylabel('True label')
plt.xlabel('Predicted label')
import itertools
lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred_undersample = lr.predict(X_test_undersample.values)
# Compute confusion matrix
# confusion_matrix 得到混淆矩陣,右下角是兩正例
cnf_matrix = confusion_matrix(y_test_undersample,y_pred_undersample)
print(cnf_matrix)
#https://blog.csdn.net/nockinonheavensdoor/article/details/80328074
np.set_printoptions(precision=2) #設定輸出為小數點後2位
print("測試集中得到的recall : ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))
# 畫非標準的混淆矩陣
class_names = [0,1] #值集合
plt.figure()
plot_confusion_matrix(cnf_matrix
, classes=class_names
, title='Confusion matrix')
plt.show()
#設定邏輯迴歸閾值 本來sigmoid 是》=0.5 當作1,可以調整一下,使為1變難
lr = LogisticRegression(C = 0.01, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
# predict 直接返回預測到的結果,預設>=0.5就是他
# predict_proba 返回的是預測屬於某標籤的概率(如 = 1的概率為 0.6,會返回0.6而不是1)
y_pred_undersample_proba = lr.predict_proba(X_test_undersample.values)
thresholds = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] #sigmoid 閾值
plt.figure(figsize=(10,10))
j = 1
for i in thresholds:
#大於閾值的 就當1
y_test_predictions_high_recall = y_pred_undersample_proba[:,1] > i
plt.subplot(3,3,j) # 第j/9 個子圖
j+=1
#得到混淆矩陣
cnf_matrix = confusion_matrix(y_test_undersample,y_test_predictions_high_recall)
np.set_printoptions(precision=2)
print("測試集中得到的recall : ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))
class_names = [0,1]
plot_confusion_matrix(cnf_matrix
, classes=class_names
, title='Threshold >= %s'%i)
plt.show()
#過取樣
#SMOTR : 找到少數累樣本
import pandas as pd
from imblearn.over_sampling import SMOTE #過取樣
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
credit_cards=pd.read_csv('data/creditcard.csv')
columns=credit_cards.columns
# The labels are in the last column ('Class'). Simply remove it to obtain features columns
features_columns=columns.delete(len(columns)-1)
features=credit_cards[features_columns]
labels=credit_cards['Class']
#切分,先分出80%的訓練集,再對訓練集進行交叉驗證,不動測試集
features_train, features_test, labels_train, labels_test = train_test_split(features,
labels,
test_size=0.2,
random_state=0)
#過取樣
oversampler = SMOTE(random_state=0)
#放入訓練資料,自動進行過取樣
os_features,os_labels=oversampler.fit_sample(features_train,labels_train)
len(os_labels[os_labels==1]) #=1的多了很多
#w為了得到最好的引數
os_features = pd.DataFrame(os_features) #得到屬性的資料
os_labels = pd.DataFrame(os_labels) #得到屬性的值
best_c = printing_Kfold_scores(os_features,os_labels) #進行混淆矩陣和recall的計算
#得到最好的引數,然後就對20%訓練集開始下手,看看效果如何
import itertools
lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(os_features,os_labels.values.ravel())
#對 一開始的20%訓練集進行測試了
y_pred = lr.predict(features_test.values)
# Compute confusion matrix
cnf_matrix = confusion_matrix(labels_test,y_pred)
np.set_printoptions(precision=2)
print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))
# Plot non-normalized confusion matrix
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix
, classes=class_names
, title='Confusion matrix')
plt.show()