python贝叶斯优化算法_自动调参——贝叶斯优化算法hyperopt

注:转载请注明出处。

本篇文章主要记录了贝叶斯优化算法hyperopt的学习笔记,如果想看自动化调参中的网格调参和遗传优化算法TPOT,请查看我另外两篇文章:网格搜索gridSearchCV和遗传优化算法TPOT。

1、算法思想

贝叶斯优化算法与网格搜索和随机搜索完全不同,会充分利用之前测试点的信息。贝叶斯优化算法通过对目标函数形状进行学习,找到使目标函数想全局最优提升的参数。

2、具体步骤首先根据先验分布,假设一个搜索函数。

然后每次使用新的测试点来测试目标函数时,利用这个信息来更新目标函数的先验分布。

最后,算法测试由后验分布给出的全局最值可能出现的位置的点。

3、缺陷与弥补缺陷:一旦找到一个局部最优,会在该区域不断地采样,很容易陷入局部最优值。

弥补方式:在探索和利用之间找到一个平衡点。“探索”就是在还未取样的区域获取采样点;利用是在根据后验分布在最可能出现全局最值的区域进行采样。

4、具体实现-python库 hyperopt

1. 功能可以针对某个模型进行调优。

可以同时调整多个模型的超参,并取得全局最优模型。–棒棒棒!!

2. hyperopt 参数简介需导入模块:hyperopt

调用方法和主要参数

1

2

3

4

5

6

7from hyperopt import fmin, tpe, hp

best = fmin(

fn=lambda x: x,

space=hp.uniform('x', 0, 1),

algo=tpe.suggest,

max_evals=100)

print best

fmin:作用就是在有限的迭代次数下,求使目标函数fn取得最小值的超参数(超参数的阈值在space中),在space中搜索超参数的方法使由algo进行指定。

fn :目标函数当不是求最小值时,需要转化为求最小值。

space:超参数的阈值空间。

algo:超参数搜索算法

max_evals: 最大迭代次数

输出历史结果,甚至进行可视化:trails matplotlib.pyplot

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

29from hyperopt import STATUS_OK,Trials

fspace={

'x': hp.uniform('x',-5,5)

}

def f(params):

x=params['x']

val=x**2

return {'loss': val,'status': STATUS_OK}

trials = Trials()

best1=fmin(fn=f,space=fspace,algo=tpe.suggest,max_evals=500,trials=trials)

print(best1)

print('trials:')

for trial in trials.trials[:10]:

print(trial)

## 可视化

# x随时间t的变化

import matplotlib.pyplot as plt

f, ax = plt.subplots(1)

xs = [t['tid'] for t in trials.trials]

ys = [t['misc']['vals']['x'] for t in trials.trials]

ax.set_xlim(xs[0]-10, xs[-1]+10)

ax.scatter(xs, ys, s=20, linewidth=0.01, alpha=0.75)

ax.set_title('$x$ $vs$ $t$ ', fontsize=18)

ax.set_xlabel('$t$', fontsize=16)

ax.set_ylabel('$x$', fontsize=16)

plt.show()

输出图片结果:由图片可以看出最初算法从整个范围中均匀地选择值,但随着时间的推移以及参数对目标函数的影响了解越来越多,该算法越来越聚焦于它认为会取得最大收益的区域-一个接近0的范围。它仍然探索整个解空间,但频率有所下降。

1

2

3

4

5

6

7

8

9

10

11# 目标函数随时间t的变化

import matplotlib.pyplot as plt

f, ax = plt.subplots(1)

xs = [t['tid'] for t in trials.trials]

ys = [t['result']['loss'] for t in trials.trials]

ax.set_xlim(xs[0]-10, xs[-1]+10)

ax.scatter(xs, ys, s=20, linewidth=0.01, alpha=0.75)

ax.set_title('$y$ $vs$ $t$ ', fontsize=18)

ax.set_xlabel('$t$', fontsize=16)

ax.set_ylabel('$y$', fontsize=16)

plt.show()

输出图片结果:可以看出目标函数逐渐趋向最小值0.

目标函数与x的变化

1

2

3

4

5

6

7

8

9import matplotlib.pyplot as plt

f, ax = plt.subplots(1)

xs = [t['misc']['vals']['x'] for t in trials.trials]

ys = [t['result']['loss'] for t in trials.trials]

ax.scatter(xs, ys, s=20, linewidth=0.01, alpha=0.75)

ax.set_title('$y$ $vs$ $x$ ', fontsize=18)

ax.set_xlabel('$x$', fontsize=16)

ax.set_ylabel('$y$', fontsize=16)

plt.show()

输出图片结果:可以看出在y取最小值处,点比较密集。

功能2:

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

63digits = datasets.load_digits()

X = digits.data

y = digits.target

print X.shape, y.shape

def hyperopt_train_test(params):

t = params['type']

del params['type']

if t == 'naive_bayes':

clf = BernoulliNB(**params)

elif t == 'svm':

clf = SVC(**params)

elif t == 'dtree':

clf = DecisionTreeClassifier(**params)

elif t == 'knn':

clf = KNeighborsClassifier(**params)

else:

return 0

return cross_val_score(clf, X, y).mean()

space = hp.choice('classifier_type', [

{

'type': 'naive_bayes',

'alpha': hp.uniform('alpha', 0.0, 2.0)

},

{

'type': 'svm',

'C': hp.uniform('C', 0, 10.0),

'kernel': hp.choice('kernel', ['linear', 'rbf']),

'gamma': hp.uniform('gamma', 0, 20.0)

},

{

'type': 'randomforest',

'max_depth': hp.choice('max_depth', range(1,20)),

'max_features': hp.choice('max_features', range(1,5)),

'n_estimators': hp.choice('n_estimators', range(1,20)),

'criterion': hp.choice('criterion', ["gini", "entropy"]),

'scale': hp.choice('scale', [0, 1]),

'normalize': hp.choice('normalize', [0, 1])

},

{

'type': 'knn',

'n_neighbors': hp.choice('knn_n_neighbors', range(1,50))

}

])

count = 0

best = 0

def f(params):

global best, count

count += 1

acc = hyperopt_train_test(params.copy())

if acc > best:

print 'new best:', acc, 'using', params['type']

best = acc

if count % 50 == 0:

print 'iters:', count, ', acc:', acc, 'using', params

return {'loss': -acc, 'status': STATUS_OK}

trials = Trials()

best = fmin(f, space, algo=tpe.suggest, max_evals=1500, trials=trials)

print 'best:'

print best

5、参考

你可能感兴趣的:(python贝叶斯优化算法)