邏輯迴歸引數詳解
阿新 • • 發佈:2020-08-11
邏輯迴歸方法:
class sklearn.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='lbfgs', max_iter=100, multi_class='auto', verbose=0, warm_start=False, n_jobs=None, l1_ratio=None)
可選引數:
-
penalty:正則化方式,可選擇‘l1’, ‘l2’, ‘elasticnet’, ‘none’,預設'l2'
-
dual:是否選擇對偶,當n_samples> n_features時,首選dual = False
-
tol:演算法停止的誤差條件,預設是0.0001
-
C:正則強度的倒數;必須為正浮點數,較小的值指定更強的正則化,預設為1.0
-
fit_intercept:是否應將常量(也稱為偏差或截距)新增到決策函式。預設是True。
-
intercept_scaling:不常用
-
class_weight:對類別進行加權,可以使用字典形式加權,輸入‘balanced’代表權重為類別頻率,預設是"None"。
-
random_state:選擇隨機種子,打亂樣本時候指定
-
solver:指定優化器型別,可選‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’
具體的優化方法參考:機器學習中的優化演算法!
-
max_iter:演算法收斂的最大迭代次數,預設100。
-
multi_class:不常用。
-
verbose:對於liblinear和lbfgs,求解器將verbose設定為任何正數以表示詳細程度。
-
warm_start:不常用。
-
n_jobs:使用核心數。
-
l1_ratio:彈性網路引數,其中0 <= l1_ratio <=1。僅當penalty=“ elasticnet”時使用。
返回標籤:
- classes_:返回的類別標籤
- coef_:係數
- intercept_:截距項
- n_iter_:所有類的迭代次數
程式碼展示
# -*- coding: utf-8 -*- """ Created on Tue Aug 11 10:12:48 2020 @author: Admin """ # 引入資料 from sklearn import datasets import numpy as np iris = datasets.load_iris() X = iris.data[:,[2,3]] y = iris.target print("Class labels:",np.unique(y)) #列印分類類別的種類 # 切分訓練資料和測試資料 from sklearn.model_selection import train_test_split ## 30%測試資料,70%訓練資料,stratify=y表示訓練資料和測試資料具有相同的類別比例 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=1,stratify=y) from sklearn.preprocessing import StandardScaler sc = StandardScaler() ## 估算訓練資料中的mu和sigma sc.fit(X_train) ## 使用訓練資料中的mu和sigma對資料進行標準化 X_train_std = sc.transform(X_train) X_test_std = sc.transform(X_test) ## 畫出決策邊界圖(只有在2個特徵才能畫出來) import matplotlib.pyplot as plt %matplotlib inline from matplotlib.colors import ListedColormap def plot_decision_region(X,y,classifier,resolution=0.02): markers = ('s','x','o','^','v') colors = ('red','blue','lightgreen','gray','cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # plot the decision surface x1_min,x1_max = X[:,0].min()-1,X[:,0].max()+1 x2_min,x2_max = X[:,1].min()-1,X[:,1].max()+1 xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,resolution), np.arange(x2_min,x2_max,resolution)) Z = classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1,xx2,Z,alpha=0.3,cmap=cmap) plt.xlim(xx1.min(),xx1.max()) plt.ylim(xx2.min(),xx2.max()) # plot class samples for idx,cl in enumerate(np.unique(y)): plt.scatter(x=X[y==cl,0], y = X[y==cl,1], alpha=0.8, c=colors[idx], marker = markers[idx], label=cl, edgecolors='black') #邏輯迴歸 由於標籤有三類,特徵有2個,因此截距和係數也有三對 from sklearn.linear_model import LogisticRegression lr = LogisticRegression(C=100.0,random_state=1) lr.fit(X_train_std,y_train) print("Class:",lr.classes_) print("Coef:",lr.coef_) print("intercept",lr.intercept_) print("n_iter",lr.n_iter_) ''' Class: [0 1 2] Coef: [[-5.61268224 -4.30718677] [ 2.40969576 -2.07325711] [ 9.51524418 5.39484899]] intercept [-5.8391281 -0.75730853 -9.21167569] n_iter [9] ''' plot_decision_region(X_train_std,y_train,classifier=lr,resolution=0.02) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.show() # 預測 ## 預測前三樣本在各個類別的概率 print("前三樣本在各個類別的預測概率為:\n",lr.predict_proba(X_test_std[:3,:])) print("\n============================") ## 獲得前三個樣本的分類標籤 print("\n前三樣本在各個類別的預測類別為:\n",lr.predict(X_test_std[:3,:])) print("\n============================") ''' 前三樣本在各個類別的預測概率為: [[3.17983737e-08 1.44886616e-01 8.55113353e-01] [8.33962295e-01 1.66037705e-01 4.55557009e-12] [8.48762934e-01 1.51237066e-01 4.63166788e-13]] ============================ 前三樣本在各個類別的預測類別為: [2 0 0] ============================ '''