机器学习中的优化方法 网格搜素
网格搜索法是指定参数值的一种穷举搜索方法,通过将估计函数的参数通过交叉验证的方法进行优化来得到最优的学习算法。 
即,将各个参数可能的取值进行排列组合,列出所有可能的组合结果生成“网格”。然后将各组合用于SVM等机器学习方法训练,并使用交叉验证对表现进行评估。在拟合函数尝试了所有的参数组合后,返回一个合适的分类器,自动调整至最佳参数组合,可以通过clf.best_params_获得参数值。

交叉验证与网格搜索

交叉验证与网格搜索是机器学习中的两个非常重要且基本的概念,但是这两个概念在刚入门的时候并不是非常容易理解与掌握,自己开始学习的时候,对这两个概念理解的并不到位,现在写一篇关于交叉验证与网格搜索的文章,将这两个基本的概念做一下梳理。

网格搜索

网格搜索(Grid Search)名字非常大气,但是用简答的话来说就是你手动的给出一个模型中你想要改动的所用的参数,程序自动的帮你使用穷举法来将所用的参数都运行一遍。决策树中我们常常将最大树深作为需要调节的参数;AdaBoost中将弱分类器的数量作为需要调节的参数。

评分方法

为了确定搜索参数,也就是手动设定的调节的变量的值中,那个是最好的,这时就需要使用一个比较理想的评分方式(这个评分方式是根据实际情况来确定的可能是accuracy、f1-score、f-beta、pricise、recall等)

交叉验证

有了好的评分方式,但是只用一次的结果就能说明某组的参数组合比另外的参数组合好吗?这显然是不严谨的,上小学的时候老师就告诉我们要求平均��。所以就有了交叉验证这一概念。下面以K折交叉验证为例介绍这一概念。

  1. 首先进行数据分割  将原始数据集分为训练集和测试集。如下图以8:2的方式分割:  png训练集使用来训练模型,测试集使用来测试模型的准确率。  注意:绝对不能使用测试集来训练数据,这相当于考试的时候先让你把考试的答案背过了,又让你参加考试。
  2. 数据验真  在k折交叉验证方法中其中K-1份作为训练数据,剩下的一份作为验真数据:

png1  这个过程一共需要进行K次,将最后K次使用实现选择好的评分方式的评分求平均返回,然后找出最大的一个评分对用的参数组合。这也就完成了交叉验证这一过程。

### 举例 下面使用一个简单的例子(预测年收入是否大于5万美元)来进行说明网格搜索与交叉验证的使用。 数据集来自[UCI机器学习知识库](https://archive.ics.uci.edu/ml/datasets/Census+Income)。
import numpy as np
import pandas as pd
from IPython.display import display
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import make_scorer, fbeta_score, accuracy_score
from sklearn.model_selection import GridSearchCV, KFold

%matplotlib inline 

data = pd.read_csv("census.csv")

# 将数据切分成特征和标签
income_raw = data['income']
features_raw = data.drop('income', axis=1)

# 显示部分数据
# display(features_raw.head(n=1))

# 因为原始数据中的,capital-gain 和 capital-loss的倾斜度非常高,所以要是用对数转换。
skewed = ['capital-gain', 'capital-loss']
features_raw[skewed] = data[skewed].apply(lambda x: np.log(x + 1))

# 归一化数字特征,是为了保证所有的特征均被平等的对待
scaler = MinMaxScaler()
numerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']
features_raw[numerical] = scaler.fit_transform(data[numerical])
# display(features_raw.head(n=1))

# 独热编码,将非数字的形式转化为数字
features = pd.get_dummies(features_raw)
income = income_raw.replace(['>50K', ['<=50K']], [1, 0])

# 切分数据集
X_train, X_test, y_train, y_test = train_test_split(features, income, test_size=0.2, random_state=0)

# Adaboost
from sklearn.ensemble import AdaBoostClassifier
clf_Ada = AdaBoostClassifier(random_state=0)

# 决策树
from sklearn.tree import DecisionTreeClassifier
clf_Tree = DecisionTreeClassifier(random_state=0)

# KNN
from sklearn.neighbors import KNeighborsClassifier
clf_KNN = KNeighborsClassifier()

# SVM
from sklearn.svm import SVC
clf_svm = SVC(random_state=0)

# Logistic
from sklearn.linear_model import LogisticRegression
clf_log = LogisticRegression(random_state=0)

# 随机森林
from sklearn.ensemble import RandomForestClassifier
clf_forest = RandomForestClassifier(random_state=0)

# GBDT
from sklearn.ensemble import GradientBoostingClassifier
clf_gbdt = GradientBoostingClassifier(random_state=0)

# GaussianNB
from sklearn.naive_bayes import GaussianNB
clf_NB = GaussianNB()

scorer = make_scorer(accuracy_score)

# 参数调优

kfold = KFold(n_splits=10)
# 决策树
parameter_tree = {'max_depth': xrange(1, 10)}
grid = GridSearchCV(clf_Tree, parameter_tree, scorer, cv=kfold)
grid = grid.fit(X_train, y_train)

print "best score: {}".format(grid.best_score_)
display(pd.DataFrame(grid.cv_results_).T)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
best score: 0.855737070514
.dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; }
 012345678
mean_fit_time0.05625350.06921330.08851260.1102330.1283370.1587190.171240.1936370.223979
mean_score_time0.002404740.002282120.002215290.00260470.002267720.002542970.002314810.002466960.00256622
mean_test_score0.751140.8238110.8393450.8399260.8466710.8523920.8515080.8531390.855737
mean_train_score0.751140.824210.8396280.8405030.8478780.8533290.8552640.8592020.863667
param_max_depth123456789
params{u’max_depth’: 1}{u’max_depth’: 2}{u’max_depth’: 3}{u’max_depth’: 4}{u’max_depth’: 5}{u’max_depth’: 6}{u’max_depth’: 7}{u’max_depth’: 8}{u’max_depth’: 9}
rank_test_score987653421
split0_test_score0.7606410.82670.8438360.8446660.8515750.8557210.8554450.860420.859038
split0_train_score0.7500840.8238280.8391840.839430.8475380.8529130.8542950.8599470.863233
split1_test_score0.7581540.8211720.8391380.8424540.8452180.8496410.8477060.8507460.852957
split1_train_score0.7503610.8244420.8397060.8459110.8500880.8542030.8558310.8614820.864984
split2_test_score0.7548370.8242120.8402430.840520.84660.8546160.8543390.8540630.856551
split2_train_score0.7507290.8247180.8390310.8393070.8473230.8522370.8542030.8595780.86397
split3_test_score0.731620.8206190.8380320.8383080.84660.8507460.8485350.8468770.852957
split3_train_score0.7533090.8245030.8398290.8401060.8483370.8537420.855370.8581040.863171
split4_test_score0.7465450.8186840.833610.8338860.839690.8479820.8454950.850470.848811
split4_train_score0.7516510.8247180.8403210.8405970.8448970.8535580.8583190.8619120.864922
split5_test_score0.7542840.8261470.8449420.8452180.8540630.8590380.857380.8582090.861802
split5_train_score0.7507910.8238890.8390610.8393380.8473230.8527290.8541110.8569670.862741
split6_test_score0.7542840.8253180.8380320.8377560.8454950.8485350.8485350.8521280.857103
split6_train_score0.7507910.8239810.8398290.8401670.8484290.8537730.8556470.8577660.863141
split7_test_score0.7497930.8213990.8354990.8354990.8446230.852640.8520870.8537460.85264
split7_train_score0.751290.8244160.8401110.8404180.8483720.8535010.8549450.8608110.863882
split8_test_score0.7533870.8263750.8382640.838540.844070.8520870.8529170.8523640.858446
split8_train_score0.7508910.8238640.8398030.840080.8483720.8530710.8549450.8578010.863391
split9_test_score0.7478570.8274810.8418580.8424110.848770.8529170.852640.8523640.857064
split9_train_score0.7515050.8237410.8394040.8396810.8480960.8535630.8549750.8576470.863237
std_fit_time0.01235830.004427880.005520260.006316910.00531950.01570110.004769910.006228540.0147429
std_score_time0.0005292140.0004670910.0003550280.0007606240.0004608290.0005046270.0004462890.0004452560.000449312
std_test_score0.007698980.002924640.003331180.003587760.003824960.003244060.003604140.003663890.00363761
std_train_score0.0008554820.0003661660.0004189730.001852640.001246980.0005531710.001161510.001687320.000726325


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

机器学习中的优化方法 网格搜素

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭