Sklearn-LogisticRegression邏輯迴歸(有處理樣本不均衡時設定引數的方法)

Candy_GL發表於2018-09-26

版權宣告:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/CherDW/article/details/54891073

  1. 邏輯迴歸:

可以做概率預測,也可用於分類,僅能用於線性問題。通過計算真實值與預測值的概率,然後變換成損失函式,求損失函式最小值來計算模型引數,從而得出模型。

 

  1. sklearn.linear_model.LogisticRegression官方API:

官方API:http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html

 

classsklearn.linear_model.LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=1.0,fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None,solver='liblinear', max_iter=100, multi_class='ovr', verbose=0,warm_start=False, n_jobs=1)

 

  1. 引數解讀
  • 正則化選擇引數(懲罰項的種類)

penalty: str,‘l1’or ‘l2’,default: ‘l2’

Usedto specify the norm used in the penalization. The ‘newton-cg’, ‘sag’ and‘lbfgs’ solvers support only l2 penalties.

  • LogisticRegression預設帶了正則化項。penalty引數可選擇的值為"l1"和"l2".分別對應L1的正則化和L2的正則化,預設是L2的正則化。
  • 在調參時如果我們主要的目的只是為了解決過擬合,一般penalty選擇L2正則化就夠了。但是如果選擇L2正則化發現還是過擬合,即預測效果差的時候,就可以考慮L1正則化。另外,如果模型的特徵非常多,我們希望一些不重要的特徵係數歸零,從而讓模型係數稀疏化的話,也可以使用L1正則化。
  • penalty引數的選擇會影響我們損失函式優化演算法的選擇。即引數solver的選擇,如果是L2正則化,那麼4種可選的演算法{‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’}都可以選擇。但是如果penalty是L1正則化的話,就只能選擇‘liblinear’了。這是因為L1正則化的損失函式不是連續可導的,而{‘newton-cg’, ‘lbfgs’,‘sag’}這三種優化演算法時都需要損失函式的一階或者二階連續導數。而‘liblinear’並沒有這個依賴。
  • dual: bool,default: False

Dualor primal formulation. Dual formulation is only implemented for l2 penalty withliblinear solver. Preferdual=False whenn_samples > n_features.

  • 對偶或者原始方法。Dual只適用於正則化相為l2 liblinear的情況,通常樣本數大於特徵數的情況下,預設為False。
  • C: float,default: 1.0

Inverseof regularization strength; must be a positive float. Like in support vectormachines, smaller values specify stronger regularization.

  • C為正則化係數λ的倒數,通常預設為1
  • fit_intercept: bool,default: True

Specifiesif a constant (a.k.a. bias or intercept) should be added to the decisionfunction.

  • 是否存在截距,預設存在
  • intercept_scaling: float,default 1.

Usefulonly when the solver ‘liblinear’ is used and self.fit_intercept is set to True.In this case, x becomes [x, self.intercept_scaling], i.e. a “synthetic” featurewith constant value equal to intercept_scaling is appended to the instancevector. The intercept becomes intercept_scaling * synthetic_feature_weight.

Note!the synthetic feature weight is subject to l1/l2 regularization as all otherfeatures. To lessen the effect of regularization on synthetic feature weight(and therefore on the intercept) intercept_scaling has to be increased.

僅在正則化項為"liblinear",且fit_intercept設定為True時有用。

  • 優化演算法選擇引數

solver

{‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’},default: ‘liblinear’

Algorithmto use in the optimization problem.

Forsmall datasets, ‘liblinear’ is a good choice, whereas ‘sag’ is

fasterfor large ones.

Formulticlass problems, only ‘newton-cg’, ‘sag’ and ‘lbfgs’ handle

multinomialloss; ‘liblinear’ is limited to one-versus-rest schemes.

‘newton-cg’,‘lbfgs’ and ‘sag’ only handle L2 penalty.

Notethat ‘sag’ fast convergence is only guaranteed on features with approximatelythe same scale. You can preprocess the data with a scaler fromsklearn.preprocessing.

Newin version 0.17: Stochastic Average Gradient descent solver.

 

  • solver引數決定了我們對邏輯迴歸損失函式的優化方法,有四種演算法可以選擇,分別是:

a) liblinear:使用了開源的liblinear庫實現,內部使用了座標軸下降法來迭代優化損失函式。

b) lbfgs:擬牛頓法的一種,利用損失函式二階導數矩陣即海森矩陣來迭代優化損失函式。

c) newton-cg:也是牛頓法家族的一種,利用損失函式二階導數矩陣即海森矩陣來迭代優化損失函式。

d) sag:即隨機平均梯度下降,是梯度下降法的變種,和普通梯度下降法的區別是每次迭代僅僅用一部分的樣本來計算梯度,適合於樣本資料多的時候。

  • 從上面的描述可以看出,newton-cg, lbfgs和sag這三種優化演算法時都需要損失函式的一階或者二階連續導數,因此不能用於沒有連續導數的L1正則化,只能用於L2正則化。而liblinear通吃L1正則化和L2正則化。
  • 同時,sag每次僅僅使用了部分樣本進行梯度迭代,所以當樣本量少的時候不要選擇它,而如果樣本量非常大,比如大於10萬,sag是第一選擇。但是sag不能用於L1正則化,所以當你有大量的樣本,又需要L1正則化的話就要自己做取捨了。要麼通過對樣本取樣來降低樣本量,要麼回到L2正則化。
  • 從上面的描述,大家可能覺得,既然newton-cg, lbfgs和sag這麼多限制,如果不是大樣本,我們選擇liblinear不就行了嘛!錯,因為liblinear也有自己的弱點!我們知道,邏輯迴歸有二元邏輯迴歸和多元邏輯迴歸。對於多元邏輯迴歸常見的有one-vs-rest(OvR)和many-vs-many(MvM)兩種。而MvM一般比OvR分類相對準確一些。鬱悶的是liblinear只支援OvR,不支援MvM,這樣如果我們需要相對精確的多元邏輯迴歸時,就不能選擇liblinear了。也意味著如果我們需要相對精確的多元邏輯迴歸不能使用L1正則化了。
  • 總結幾種優化演算法適用情況:

 L1

liblinear

liblinear適用於小資料集;如果選擇L2正則化發現還是過擬合,即預測效果差的時候,就可以考慮L1正則化;如果模型的特徵非常多,希望一些不重要的特徵係數歸零,從而讓模型係數稀疏化的話,也可以使用L1正則化。

L2

liblinear

libniear只支援多元邏輯迴歸的OvR,不支援MvM,但MVM相對精確。

L2

lbfgs/newton-cg/sag

較大資料集,支援one-vs-rest(OvR)和many-vs-many(MvM)兩種多元邏輯迴歸。

L2

sag

如果樣本量非常大,比如大於10萬,sag是第一選擇;但不能用於L1正則化。

    具體OvR和MvM有什麼不同下一節講。

 

  • 分類方式選擇引數

multi_class: str,{‘ovr’, ‘multinomial’},default:‘ovr’

Multiclassoption can be either ‘ovr’ or ‘multinomial’. If the option chosen is ‘ovr’,then a binary problem is fit for each label. Else the loss minimised is themultinomial loss fit across the entire probability distribution. Works only forthe ‘newton-cg’, ‘sag’ and ‘lbfgs’ solver.

Newin version 0.18: Stochastic Average Gradient descent solver for ‘multinomial’case.

  • ovr即前面提到的one-vs-rest(OvR),而multinomial即前面提到的many-vs-many(MvM)。如果是二元邏輯迴歸,ovr和multinomial並沒有任何區別,區別主要在多元邏輯迴歸上。
  • OvRMvM有什麼不同

        OvR的思想很簡單,無論你是多少元邏輯迴歸,我們都可以看做二元邏輯迴歸。具體做法是,對於第K類的分類決策,我們把所有第K類的樣本作為正例,除了第K類樣本以外的所有樣本都作為負例,然後在上面做二元邏輯迴歸,得到第K類的分類模型。其他類的分類模型獲得以此類推。

        而MvM則相對複雜,這裡舉MvM的特例one-vs-one(OvO)作講解。如果模型有T類,我們每次在所有的T類樣本里面選擇兩類樣本出來,不妨記為T1類和T2類,把所有的輸出為T1和T2的樣本放在一起,把T1作為正例,T2作為負例,進行二元邏輯迴歸,得到模型引數。我們一共需要T(T-1)/2次分類。

        可以看出OvR相對簡單,但分類效果相對略差(這裡指大多數樣本分佈情況,某些樣本分佈下OvR可能更好)。而MvM分類相對精確,但是分類速度沒有OvR快。如果選擇了ovr,則4種損失函式的優化方法liblinear,newton-cg,lbfgs和sag都可以選擇。但是如果選擇了multinomial,則只能選擇newton-cg, lbfgs和sag了。

  • 型別權重引數:(考慮誤分類代價敏感、分類型別不平衡的問題)

class_weight: dictor ‘balanced’,default: None

Weightsassociated with classes in the form {class_label: weight}. If not given, allclasses are supposed to have weight one.

The“balanced” mode uses the values of y to automatically adjust weights inverselyproportional to class frequencies in the input data as n_samples / (n_classes *np.bincount(y)).

Notethat these weights will be multiplied with sample_weight (passed through thefit method) if sample_weight is specified.

Newin version 0.17: class_weight=’balanced’ instead of deprecatedclass_weight=’auto’.

  • class_weight引數用於標示分類模型中各種型別的權重,可以不輸入,即不考慮權重,或者說所有型別的權重一樣。如果選擇輸入的話,可以選擇balanced讓類庫自己計算型別權重,或者我們自己輸入各個型別的權重,比如對於0,1的二元模型,我們可以定義class_weight={0:0.9, 1:0.1},這樣型別0的權重為90%,而型別1的權重為10%。
  • 如果class_weight選擇balanced,那麼類庫會根據訓練樣本量來計算權重。某種型別樣本量越多,則權重越低,樣本量越少,則權重越高。當class_weight為balanced時,類權重計算方法如下:n_samples / (n_classes * np.bincount(y))

n_samples為樣本數,n_classes為類別數量,np.bincount(y)會輸出每個類的樣本數,例如y=[1,0,0,1,1],則np.bincount(y)=[2,3]

  • 那麼class_weight有什麼作用呢?

       在分類模型中,我們經常會遇到兩類問題:

        第一種是誤分類的代價很高。比如對合法使用者和非法使用者進行分類,將非法使用者分類為合法使用者的代價很高,我們寧願將合法使用者分類為非法使用者,這時可以人工再甄別,但是卻不願將非法使用者分類為合法使用者。這時,我們可以適當提高非法使用者的權重。

       第二種是樣本是高度失衡的,比如我們有合法使用者和非法使用者的二元樣本資料10000條,裡面合法使用者有9995條,非法使用者只有5條,如果我們不考慮權重,則我們可以將所有的測試集都預測為合法使用者,這樣預測準確率理論上有99.95%,但是卻沒有任何意義。這時,我們可以選擇balanced,讓類庫自動提高非法使用者樣本的權重。

       提高了某種分類的權重,相比不考慮權重,會有更多的樣本分類劃分到高權重的類別,從而可以解決上面兩類問題。

       當然,對於第二種樣本失衡的情況,我們還可以考慮用下一節講到的樣本權重引數:sample_weight,而不使用class_weight。sample_weight在下一節講。

  • 樣本權重引數

sample_weight(fit函式引數)

  • 當樣本是高度失衡的,導致樣本不是總體樣本的無偏估計,從而可能導致我們的模型預測能力下降。遇到這種情況,我們可以通過調節樣本權重來嘗試解決這個問題。調節樣本權重的方法有兩種第一種是在class_weight使用balanced。第二種是在呼叫fit函式時,通過sample_weight來自己調節每個樣本權重。在scikit-learn做邏輯迴歸時,如果上面兩種方法都用到了,那麼樣本的真正權重是class_weight*sample_weight.
  • max_iter: int,default: 100

Usefulonly for the newton-cg, sag and lbfgs solvers. Maximum number of iterationstaken for the solvers to converge.

  • 僅在正則化優化演算法為newton-cg, sag and lbfgs才有用,演算法收斂的最大迭代次數。
  • random_state: int seed, RandomState instance,default: None

The seed of the pseudo random number generator touse when shuffling the data. Used only in solvers ‘sag’ and ‘liblinear’.

  • 隨機數種子,預設為無,僅在正則化優化演算法為sag,liblinear時有用。
  • tol :float,default: 1e-4

Tolerance for stopping criteria.迭代終止判據的誤差範圍。

  • verbose: int, default: 0

Forthe liblinear and lbfgs solvers set verbose to any positive number forverbosity.

  • 日誌冗長度int:冗長度;0:不輸出訓練過程;1:偶爾輸出;>1:對每個子模型都輸出
  • warm_start: bool,default: False

Whenset to True, reuse the solution of the previous call to fit as initialization,otherwise, just erase the previous solution. Useless for liblinear solver.

Newin version 0.17: warm_start to support lbfgs, newton-cg, sag solvers.

  • 是否熱啟動,如果是,則下一次訓練是以追加樹的形式進行(重新使用上一次的呼叫作為初始化),bool:熱啟動,False:預設值
  • n_jobs: int, default: 1

Numberof CPU cores used during the cross-validation loop. If given a value of -1, allcores are used.

  • 並行數,int:個數;-1:跟CPU核數一致;1:預設值

 

  1. LogisticRegression類中的方法

LogisticRegression類中的方法有如下幾種,常用的是fit和predict

  • fit(X, y, sample_weight=None)

Fitthe model according to the given training data.

Parameters:        

X: {array-like, sparse matrix}, shape (n_samples, n_features)

Trainingvector, where n_samples is the number of samples and n_features is the numberof features.

y: array-like, shape (n_samples,)

Targetvector relative to X.

sample_weight:array-like, shape (n_samples,)optional

Arrayof weights that are assigned to individual samples. If not provided, then eachsample is given unit weight.

Newin version 0.17: sample_weight support to LogisticRegression.

Returns:        

self: object

Returnsself.

  • 擬合模型,用來訓練LR分類器,其中X是訓練樣本,y是對應的標記向量
  • fit_transform(X, y=None, **fit_params)

Fitto data, then transform it.

Fitstransformer to X and y with optional parameters fit_params and returns atransformed version of X.

Parameters:        

X: numpy array of shape [n_samples, n_features]

Trainingset.

y: numpy array of shape [n_samples]

Targetvalues.

Returns:        

X_new: numpy array of shape [n_samples, n_features_new]

Transformedarray.

  • fit與transform的結合,先fit後transform
  • transform(*args, **kwargs)

DEPRECATED:Support to use estimators as feature selectors will be removed in version 0.19.Use SelectFromModel instead.

ReduceX to its most important features.

Usescoef_ or feature_importances_ to determine the most important features. Formodels with a coef_ for each class, the absolute sum over the classes is used.

Parameters:        

X: array or scipy sparse matrix of shape [n_samples, n_features]

Theinput samples.

Threshold:string, float or None, optional (default=None)

The threshold value to use for featureselection. Features whose importance is greater or equal are kept while theothers are discarded.If “median” (resp. “mean”), then the thresholdvalue is the median (resp. the mean) of the feature importances. A scalingfactor (e.g., “1.25*mean”) may also be used. If None and if available, theobject attribute threshold is used. Otherwise,“mean” is used by default.

Returns:        

X_r: array of shape [n_samples, n_selected_features]

Theinput samples with only the selected features.

  •  預設使用特徵重要性平均值作為閾值對特徵進行篩選
  • predict(X)[source]

Predictclass labels for samples in X.

Parameters:        

X: {array-like, sparse matrix}, shape = [n_samples, n_features]

Samples.

Returns:        

C: array, shape = [n_samples]

Predictedclass label per sample.

用來預測樣本的標記,也就是分類,X是測試集

  • predict_proba(X)

Probabilityestimates.

The returned estimates for all classes areordered by the label of classes.

Fora multi_class problem, if multi_class is set to be “multinomial” the softmaxfunction is used to find the predicted probability of each class. Else use aone-vs-rest approach, i.e calculate the probability of each class assuming itto be positive using the logistic function. and normalize these values acrossall the classes.

Parameters:        

X :array-like, shape = [n_samples, n_features]

Returns:        

T :array-like, shape = [n_samples, n_classes]

Returns the probability of the sample foreach class in the model, where classes are ordered as they are inself.classes_.

  • 輸出分類概率。返回每種類別的概率,按照分類類別順序給出。如果是多分類問題,multi_class="multinomial",則會給出樣本對於每種類別的概率。
  1. 示例

 


 
  1. #分開訓練集、測試集

  2. train= loan_data.iloc[0: 55596, :]

  3. test= loan_data.iloc[55596:, :]

  4. # 避免過擬合,採用交叉驗證,驗證集佔訓練集20%,固定隨機種子(這裡所用的資料都是在訓練集上進行)

  5. train_X,test_X, train_y, test_y = train_test_split(train,

  6. target,

  7. test_size = 0.2,

  8. random_state = 0)

  9. train_y= train_y['label']

  10. test_y= test_y['label']

  11. # 用Logistic迴歸建模

  12. lr_model= LogisticRegression(C = 1.0,

  13. penalty = 'l2')

  14. lr_model.fit(train_X,train_y)

  15. # 給出交叉驗證集的預測結果,並輸出評估的準確率、召回率、F1值

  16. pred_test= lr_model.predict(test_X)

  17. printclassification_report(test_y, pred_test)

  18. # 輸出測試集使用者逾期還款概率,predict_proba會輸出兩個概率,即分別分類為‘0’和‘1’的概率,這裡只取‘1’的概率

  19. pred= lr_model.predict_proba(test)

  20. result= pd.DataFrame(pred)

  21. result.index= test.index

  22. result.columns= ['0', 'probability']

  23. result.drop('0',

  24. axis = 1,

  25. inplace = True)

  26. printresult.head(5)

  27. #輸出結果

  28. result.to_csv('result.csv')


 

--------------------- 本文來自 Cherzhoucheer 的CSDN 部落格 ,全文地址請點選:https://blog.csdn.net/cherdw/article/details/54891073?utm_source=copy 

相關文章