sklearn使用——梯度下降及逻辑回归

Posted on 2018-11-15 17:43  岚月  阅读(523)  评论(0编辑  收藏  举报

一:梯度下降:

梯度下降本质上是对极小值的无限逼近。先求得梯度,再取其反方向,以定步长在此方向上走一步,下次计算则从此点开始,一步步接近极小值。需要注意的是步长的取值,如果过小,则需要多次迭代,耗费大量时间才能取得极小值;如果过大,则可能难以取得较为接近极小值的点,在极小值两边来回跳跃,无法接近极小值。

而步长的取值往往于梯度有关,如果梯度的值较大,则步长可以取大的值,如果梯度较小,则步长应取较小值。

优势:高效,优化途径多

劣势:需要一些超参数:regularization(正则化)参数以及number of iterations(迭代次数),对feature scalling(特征缩放)敏感。

 1 from sklearn.linear_model import SGDClassifier as SGD
 2 
 3 x=[[0,0],[1,1]]
 4 y=[0,1]
 5 clf = SGD(alpha=0.0001, average=False, class_weight=None, epsilon=0.1,
 6        eta0=0.0, fit_intercept=True, l1_ratio=0.15,
 7        learning_rate='optimal', loss='hinge', max_iter=5, n_iter=None,
 8        n_jobs=1, penalty='l2', power_t=0.5, random_state=None,
 9        shuffle=True, tol=None, verbose=0, warm_start=False)
10 clf.fit(x,y)
11 print(clf.predict([[2,2]]))
12 print(clf.coef_)
13 print(clf.intercept_)
14 print(clf.decision_function([[2,2]])

根据官方网站的代码,使用了SGDClassifier分类器,进行了尝试。

 1 # coding = UTF-8
 2 from sklearn.linear_model import SGDClassifier as SGD
 3 from sklearn.datasets.samples_generator import make_blobs
 4 import matplotlib.pyplot as plt
 5 import numpy as np
 6 
 7 X,y = make_blobs(n_samples=50,centers=2,random_state=0,cluster_std=0.6)
 8 clf = SGD(loss='hinge',alpha=0.01,max_iter=200,fit_intercept=True)
 9 clf.fit(X,y)
10 print("预测1:",clf.predict([[1,10]]))
11 print("预测2:",clf.predict([[2,2]]))
12 print("回归系数:",clf.coef_)
13 print("偏差",clf.intercept_)
14 print("##################")
15 print(X.shape)
16 print(y.shape)

使用make_blobs创建数据测试。

注:

  • loss="hinge": (soft-margin) linear Support Vector Machine ((软-间隔)线性支持向量机),
  • loss="modified_huber": smoothed hinge loss (平滑的 hinge 损失),
  • loss="log": logistic regression (logistic 回归),
  • and all regression losses below(以及所有的回归损失)。

前两个 loss functions(损失函数)是懒惰的,如果一个例子违反了 margin constraint(边界约束),它们仅更新模型的参数, 这使得训练非常有效率,即使使用了 L2 penalty(惩罚)我们仍然可能得到稀疏的模型结果。

梯度下降需注意参数:

alpha:乘以正则化项的常数,默认0.0001。当被设置为‘optimal’时也被用于计算学习效率

fit_intercept:是否该截取截距,默认True。如果为‘False’则假定数据以及居中。

 

梯度下降常用方法:

fit(X,y,coef_init=None,intercept_init=None,sample_weight=None):拟合线性模型(训练)

X:{类似数组的稀疏矩阵},形式:(n_sanmples,n_features)。

y:类似数组,形式:(n_samples)。

sample_weight:数组样本,形式:(n_samples,),optional(可选),可以设定个别样本的权重,如果不设定,则默认相等。

 

predict(X):用于预测X样本中的标签(结果/分类)

X:{类似数组的稀疏矩阵},形式:[n_samples,n_features]。

 

score(X,y,samples_weight=None)::(与上方相同)用于返回测试数据和标签(结果)的平均精度。

 

 

 

二:逻辑回归(逻辑斯特增长模型):

逻辑回归实际为一种分类的线性模型。如图,值域为0~1。如果需要解决非线性问题,与支持向量机SVM的思路相同,即将特征映射到高维来解决问题。因此,也可用梯度下降来求解。

 1 import numpy as np
 2 import pandas as pd
 3 from sklearn.linear_model import LogisticRegression as Log
 4 
 5 data=[ [-0.017612,14.053064,0],
 6        [-1.395634,4.662541,1],
 7        [-0.752157,6.538620,0],
 8        [-1.322371,7.152853,0],
 9        [0.423363,11.054677,0],
10        [0.406704,7.067335,1],
11        [0.667394,12.741452,0],
12        [-2.460150,6.866805,1],
13        [0.569411,9.548755,0],
14        [-0.026632,10.427743,0],
15        [0.850433,6.920334,1],
16        [1.347183,13.175500,0],
17        [1.176813,3.167020,1],
18        [-1.781871,9.097953,0],
19        [-0.566606,5.749003,1],
20        [0.931635,1.589505,1],
21        [-0.024205,6.151823,1],
22        [-0.036453,2.690988,1],
23        [-0.196949,0.444165,1],
24        [1.014459,5.754399,1] ]
25 
26 dataMat = np.mat(data)
27 y=dataMat[:,2]
28 b=np.ones(y.shape)
29 x=np.column_stack((b,dataMat[:,0:2]))
30 x=np.mat(x)
31 
32 model = Log()
33 model.fit(x,y)
34 print(model)
35 
36 predicted = model.predict(x)
37 answer = model.predict_proba(x)
38 print (predicted)
39 print(answer)

 LogisticRegression中有这些参数需要注意:

penalty:'l1','l2'使用l1正则化,还是l2,默认l2

tol:精度为多少时可以停止计算,默认1e-4(十的负四次方)

C:C越大,正则化因子所占比例越小,C越小,正则化因子所占比例越大,默认1.0

solver:使用什么方法,默认liblinear(线性算法)。newton-cg,lbfgs,liblinear(对小数据集表现较好,大数据集建议使用sag及saga),sag(随即平均梯度下降算法Stochastic Average Gradient desqent solver),saga。

max_iter:最大迭代次数,默认100。

 

LogisticRegression常用方法:

fit(X,y,sample_weight=None):用于拟合模型(训练)

X:{类似数组的稀疏矩阵},形式:(n_samples,n_features)。

y:类似数组,形式:(n_samples)。

sample_weight:数组样本,形式:(n_samples,),optional(可选),可以设定个别样本的权重,如果不设定,则默认相等。

predict(X):用于预测X样本的标签(结果/分类)

X:同上。

返回C:数组,形式:[n_samples]

predict_proba(X):用于预测为对应标签的概率

X:同上。

返回一个n行k列的数组,n对应样本数量,k为可能的标签(结果/分类),每一行的结果之和应为1