成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

5分鐘掌握Python隨機爬山算法

開發 后端 算法
在本教程中,您將發現用于函數優化的爬山優化算法完成本教程。

 隨機爬山是一種優化算法。它利用隨機性作為搜索過程的一部分。這使得該算法適用于非線性目標函數,而其他局部搜索算法不能很好地運行。它也是一種局部搜索算法,這意味著它修改了單個解決方案并搜索搜索空間的相對局部區域,直到找到局部最優值為止。這意味著它適用于單峰優化問題或在應用全局優化算法后使用。

在本教程中,您將發現用于函數優化的爬山優化算法完成本教程后,您將知道:

  •  爬山是用于功能優化的隨機局部搜索算法。
  •  如何在Python中從頭開始實現爬山算法。
  •  如何應用爬山算法并檢查算法結果。

教程概述

本教程分為三個部分:他們是:

  •  爬山算法
  •  爬山算法的實現
  •  應用爬山算法的示例

爬山算法

隨機爬山算法是一種隨機局部搜索優化算法。它以起始點作為輸入和步長,步長是搜索空間內的距離。該算法將初始點作為當前最佳候選解決方案,并在提供的點的步長距離內生成一個新點。計算生成的點,如果它等于或好于當前點,則將其視為當前點。新點的生成使用隨機性,通常稱為隨機爬山。這意味著該算法可以跳過響應表面的顛簸,嘈雜,不連續或欺騙性區域,作為搜索的一部分。重要的是接受具有相等評估的不同點,因為它允許算法繼續探索搜索空間,例如在響應表面的平坦區域上。限制這些所謂的“橫向”移動以避免無限循環也可能是有幫助的。該過程一直持續到滿足停止條件,例如最大數量的功能評估或給定數量的功能評估內沒有改善為止。該算法之所以得名,是因為它會(隨機地)爬到響應面的山坡上,達到局部最優值。這并不意味著它只能用于最大化目標函數。這只是一個名字。實際上,通常,我們最小化功能而不是最大化它們。作為局部搜索算法,它可能會陷入局部最優狀態。然而,多次重啟可以允許算法定位全局最優。步長必須足夠大,以允許在搜索空間中找到更好的附近點,但步幅不能太大,以使搜索跳出包含局部最優值的區域。

爬山算法的實現

在撰寫本文時,SciPy庫未提供隨機爬山的實現。但是,我們可以自己實現它。首先,我們必須定義目標函數和每個輸入變量到目標函數的界限。目標函數只是一個Python函數,我們將其命名為Objective()。邊界將是一個2D數組,每個輸入變量都具有一個維度,該變量定義了變量的最小值和最大值。例如,一維目標函數和界限將定義如下: 

  1. # objective function  
  2. def objective(x):  
  3.  return 0   
  4. # define range for input  
  5. bounds = asarray([[-5.0, 5.0]]) 

接下來,我們可以生成初始解作為問題范圍內的隨機點,然后使用目標函數對其進行評估。 

  1. # generate an initial point  
  2. solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])  
  3. # evaluate the initial point  
  4. solution_eval = objective(solution) 

現在我們可以遍歷定義為“ n_iterations”的算法的預定義迭代次數,例如100或1,000。 

  1. # run the hill climb  
  2. for i in range(n_iterations): 

算法迭代的第一步是采取步驟。這需要預定義的“ step_size”參數,該參數相對于搜索空間的邊界。我們將采用高斯分布的隨機步驟,其中均值是我們的當前點,標準偏差由“ step_size”定義。這意味著大約99%的步驟將在當前點的(3 * step_size)之內。 

  1. # take a step  
  2. candidate = solution + randn(len(bounds)) * step_size 

我們不必采取這種方式。您可能希望使用0到步長之間的均勻分布。例如: 

  1. # take a step  
  2. candidate = solution + rand(len(bounds)) * step_size 

接下來,我們需要評估具有目標函數的新候選解決方案。 

  1. # evaluate candidate point  
  2. candidte_eval = objective(candidate) 

然后,我們需要檢查此新點的評估結果是否等于或優于當前最佳點,如果是,則用此新點替換當前最佳點。 

  1. # check if we should keep the new point  
  2. if candidte_eval <= solution_eval:  
  3.  # store the new point  
  4.  solution, solution_eval = candidate, candidte_eval  
  5.  # report progress  
  6.  print('>%d f(%s) = %.5f' % (i, solution, solution_eval)) 

就是這樣。我們可以將此爬山算法實現為可重用函數,該函數將目標函數的名稱,每個輸入變量的范圍,總迭代次數和步驟作為參數,并返回找到的最佳解決方案及其評估。 

  1. # hill climbing local search algorithm  
  2. def hillclimbing(objective, bounds, n_iterations, step_size):  
  3.  # generate an initial point  
  4.  solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])  
  5.  # evaluate the initial point  
  6.  solution_eval = objective(solution)  
  7.  # run the hill climb  
  8.  for i in range(n_iterations):  
  9.   # take a step  
  10.   candidate = solution + randn(len(bounds)) * step_size  
  11.   # evaluate candidate point  
  12.   candidte_eval = objective(candidate)  
  13.   # check if we should keep the new point 
  14.   if candidte_eval <= solution_eval:  
  15.    # store the new point  
  16.    solution, solution_eval = candidate, candidte_eval  
  17.    # report progress  
  18.    print('>%d f(%s) = %.5f' % (i, solution, solution_eval))  
  19.  return [solution, solution_eval] 

現在,我們知道了如何在Python中實現爬山算法,讓我們看看如何使用它來優化目標函數。

應用爬山算法的示例

在本節中,我們將把爬山優化算法應用于目標函數。首先,讓我們定義目標函數。我們將使用一個簡單的一維x ^ 2目標函數,其邊界為[-5,5]。下面的示例定義了函數,然后為輸入值的網格創建了函數響應面的折線圖,并用紅線標記了f(0.0)= 0.0處的最佳值。 

  1. # convex unimodal optimization function  
  2. from numpy import arange  
  3. from matplotlib import pyplot   
  4. # objective function  
  5. def objective(x):  
  6.  return x[0]**2.0   
  7. # define range for input  
  8. r_min, r_max = -5.0, 5.0  
  9. # sample input range uniformly at 0.1 increments  
  10. inputs = arange(r_min, r_max, 0.1)  
  11. # compute targets  
  12. results = [objective([x]) for x in inputs]  
  13. # create a line plot of input vs result  
  14. pyplot.plot(inputs, results)  
  15. # define optimal input value  
  16. x_optima = 0.0  
  17. # draw a vertical line at the optimal input  
  18. pyplot.axvline(x=x_optimals='--'color='red' 
  19. # show the plot  
  20. pyplot.show() 

運行示例將創建目標函數的折線圖,并清晰地標記函數的最優值。

接下來,我們可以將爬山算法應用于目標函數。首先,我們將播種偽隨機數生成器。通常這不是必需的,但是在這種情況下,我想確保每次運行算法時都得到相同的結果(相同的隨機數序列),以便以后可以繪制結果。 

  1. # seed the pseudorandom number generator  
  2. seed(5) 

接下來,我們可以定義搜索的配置。在這種情況下,我們將搜索算法的1,000次迭代,并使用0.1的步長。假設我們使用的是高斯函數來生成步長,這意味著大約99%的所有步長將位于給定點(0.1 * 3)的距離內,例如 三個標準差。 

  1. n_iterations = 1000  
  2. # define the maximum step size  
  3. step_size = 0.1 

接下來,我們可以執行搜索并報告結果。 

  1. # perform the hill climbing search  
  2. best, score = hillclimbing(objective, bounds, n_iterations, step_size)  
  3. print('Done!')  
  4. print('f(%s) = %f' % (best, score)) 

結合在一起,下面列出了完整的示例。 

  1. # hill climbing search of a one-dimensional objective function  
  2. from numpy import asarray  
  3. from numpy.random import randn  
  4. from numpy.random import rand  
  5. from numpy.random import seed   
  6. # objective function  
  7. def objective(x):  
  8.  return x[0]**2.0   
  9. # hill climbing local search algorithm  
  10. def hillclimbing(objective, bounds, n_iterations, step_size):  
  11.  # generate an initial point  
  12.  solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])  
  13.  # evaluate the initial point  
  14.  solution_eval = objective(solution)  
  15.  # run the hill climb  
  16.  for i in range(n_iterations): 
  17.   # take a step  
  18.   candidate = solution + randn(len(bounds)) * step_size  
  19.   # evaluate candidate point  
  20.   candidte_eval = objective(candidate)  
  21.   # check if we should keep the new point  
  22.   if candidte_eval <= solution_eval:  
  23.    # store the new point  
  24.    solution, solution_eval = candidate, candidte_eval  
  25.    # report progress  
  26.    print('>%d f(%s) = %.5f' % (i, solution, solution_eval))  
  27.  return [solution, solution_eval]  
  28. # seed the pseudorandom number generator  
  29. seed(5)  
  30. # define range for input  
  31. bounds = asarray([[-5.0, 5.0]])  
  32. # define the total iterations 
  33. n_iterations = 1000  
  34. # define the maximum step size  
  35. step_size = 0.1  
  36. # perform the hill climbing search  
  37. best, score = hillclimbing(objective, bounds, n_iterations, step_size)  
  38. print('Done!')  
  39. print('f(%s) = %f' % (best, score)) 

運行該示例將報告搜索進度,包括每次檢測到改進時的迭代次數,該函數的輸入以及來自目標函數的響應。搜索結束時,找到最佳解決方案,并報告其評估結果。在這種情況下,我們可以看到在算法的1,000次迭代中有36處改進,并且該解決方案非常接近于0.0的最佳輸入,其計算結果為f(0.0)= 0.0。 

  1. >1 f([-2.74290923]) = 7.52355  
  2. >3 f([-2.65873147]) = 7.06885  
  3. >4 f([-2.52197291]) = 6.36035  
  4. >5 f([-2.46450214]) = 6.07377  
  5. >7 f([-2.44740961]) = 5.98981  
  6. >9 f([-2.28364676]) = 5.21504  
  7. >12 f([-2.19245939]) = 4.80688  
  8. >14 f([-2.01001538]) = 4.04016  
  9. >15 f([-1.86425287]) = 3.47544  
  10. >22 f([-1.79913002]) = 3.23687  
  11. >24 f([-1.57525573]) = 2.48143  
  12. >25 f([-1.55047719]) = 2.40398  
  13. >26 f([-1.51783757]) = 2.30383  
  14. >27 f([-1.49118756]) = 2.22364  
  15. >28 f([-1.45344116]) = 2.11249  
  16. >30 f([-1.33055275]) = 1.77037  
  17. >32 f([-1.17805016]) = 1.38780  
  18. >33 f([-1.15189314]) = 1.32686  
  19. >36 f([-1.03852644]) = 1.07854  
  20. >37 f([-0.99135322]) = 0.98278  
  21. >38 f([-0.79448984]) = 0.63121  
  22. >39 f([-0.69837955]) = 0.48773  
  23. >42 f([-0.69317313]) = 0.48049  
  24. >46 f([-0.61801423]) = 0.38194  
  25. >48 f([-0.48799625]) = 0.23814  
  26. >50 f([-0.22149135]) = 0.04906  
  27. >54 f([-0.20017144]) = 0.04007  
  28. >57 f([-0.15994446]) = 0.02558  
  29. >60 f([-0.15492485]) = 0.02400  
  30. >61 f([-0.03572481]) = 0.00128  
  31. >64 f([-0.03051261]) = 0.00093  
  32. >66 f([-0.0074283]) = 0.00006  
  33. >78 f([-0.00202357]) = 0.00000  
  34. >119 f([0.00128373]) = 0.00000  
  35. >120 f([-0.00040911]) = 0.00000  
  36. >314 f([-0.00017051]) = 0.00000  
  37. Done!  
  38. f([-0.00017051]) = 0.000000 

以線圖的形式查看搜索的進度可能很有趣,該線圖顯示了每次改進后最佳解決方案的評估變化。每當有改進時,我們就可以更新hillclimbing()來跟蹤目標函數的評估,并返回此分數列表。 

  1. # hill climbing local search algorithm  
  2. def hillclimbing(objective, bounds, n_iterations, step_size):  
  3.  # generate an initial point  
  4.  solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])  
  5.  # evaluate the initial point  
  6.  solution_eval = objective(solution)  
  7.  # run the hill climb 
  8.  scores = list()  
  9.  scores.append(solution_eval)  
  10.  for i in range(n_iterations):  
  11.   # take a step  
  12.   candidate = solution + randn(len(bounds)) * step_size  
  13.   # evaluate candidate point  
  14.   candidte_eval = objective(candidate)  
  15.   # check if we should keep the new point  
  16.   if candidte_eval <= solution_eval:  
  17.    # store the new point  
  18.    solution, solution_eval = candidate, candidte_eval  
  19.    # keep track of scores  
  20.    scores.append(solution_eval)  
  21.    # report progress  
  22.    print('>%d f(%s) = %.5f' % (i, solution, solution_eval))  
  23.  return [solution, solution_eval, scores] 

然后,我們可以創建這些分數的折線圖,以查看搜索過程中發現的每個改進的目標函數的相對變化。 

  1. # line plot of best scores  
  2. pyplot.plot(scores, '.-')  
  3. pyplot.xlabel('Improvement Number')  
  4. pyplot.ylabel('Evaluation f(x)')  
  5. pyplot.show() 

結合在一起,下面列出了執行搜索并繪制搜索過程中改進解決方案的目標函數得分的完整示例。 

  1. # hill climbing search of a one-dimensional objective function  
  2. from numpy import asarray  
  3. from numpy.random import randn  
  4. from numpy.random import rand  
  5. from numpy.random import seed  
  6. from matplotlib import pyplot   
  7. # objective function  
  8. def objective(x):  
  9.  return x[0]**2.0  
  10. # hill climbing local search algorithm  
  11. def hillclimbing(objective, bounds, n_iterations, step_size):  
  12.  # generate an initial point  
  13.  solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])  
  14.  # evaluate the initial point  
  15.  solution_eval = objective(solution)  
  16.  # run the hill climb  
  17.  scores = list()  
  18.  scores.append(solution_eval)  
  19.  for i in range(n_iterations):  
  20.   # take a step  
  21.   candidate = solution + randn(len(bounds)) * step_size  
  22.   # evaluate candidate point  
  23.   candidte_eval = objective(candidate)  
  24.   # check if we should keep the new point  
  25.   if candidte_eval <= solution_eval:  
  26.    # store the new point  
  27.    solution, solution_eval = candidate, candidte_eval  
  28.    # keep track of scores  
  29.    scores.append(solution_eval)  
  30.    # report progress  
  31.    print('>%d f(%s) = %.5f' % (i, solution, solution_eval))  
  32.  return [solution, solution_eval, scores]  
  33. # seed the pseudorandom number generator  
  34. seed(5)  
  35. # define range for input  
  36. bounds = asarray([[-5.0, 5.0]])  
  37. # define the total iterations  
  38. n_iterations = 1000  
  39. # define the maximum step size  
  40. step_size = 0.1  
  41. # perform the hill climbing search  
  42. best, score, scores = hillclimbing(objective, bounds, n_iterations, step_size)  
  43. print('Done!')  
  44. print('f(%s) = %f' % (best, score))  
  45. # line plot of best scores  
  46. pyplot.plot(scores, '.-')  
  47. pyplot.xlabel('Improvement Number')  
  48. pyplot.ylabel('Evaluation f(x)')  
  49. pyplot.show() 

運行示例將執行搜索,并像以前一樣報告結果。創建一個線形圖,顯示在爬山搜索期間每個改進的目標函數評估。在搜索過程中,我們可以看到目標函數評估發生了約36個變化,隨著算法收斂到最優值,初始變化較大,而在搜索結束時變化很小,難以察覺。

鑒于目標函數是一維的,因此可以像上面那樣直接繪制響應面。通過將在搜索過程中找到的最佳候選解決方案繪制為響應面中的點,來回顧搜索的進度可能會很有趣。我們期望沿著響應面到達最優點的一系列點。這可以通過首先更新hillclimbing()函數以跟蹤每個最佳候選解決方案在搜索過程中的位置來實現,然后返回最佳解決方案列表來實現。 

  1. # hill climbing local search algorithm  
  2. def hillclimbing(objective, bounds, n_iterations, step_size):  
  3.  # generate an initial point  
  4.  solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])  
  5.  # evaluate the initial point  
  6.  solution_eval = objective(solution) 
  7.  # run the hill climb  
  8.  solutions = list()  
  9.  solutions.append(solution)  
  10.  for i in range(n_iterations):  
  11.   # take a step  
  12.   candidate = solution + randn(len(bounds)) * step_size  
  13.   # evaluate candidate point 
  14.    candidte_eval = objective(candidate)  
  15.   # check if we should keep the new point  
  16.   if candidte_eval <= solution_eval:  
  17.    # store the new point  
  18.    solution, solution_eval = candidate, candidte_eval  
  19.    # keep track of solutions  
  20.    solutions.append(solution) 
  21.    # report progress  
  22.    print('>%d f(%s) = %.5f' % (i, solution, solution_eval))  
  23.  return [solution, solution_eval, solutions] 

然后,我們可以創建目標函數響應面的圖,并像以前那樣標記最優值。 

  1. # sample input range uniformly at 0.1 increments  
  2. inputs = arange(bounds[0,0], bounds[0,1], 0.1)  
  3. # create a line plot of input vs result  
  4. pyplot.plot(inputs, [objective([x]) for x in inputs], '--')  
  5. # draw a vertical line at the optimal input  
  6. pyplot.axvline(x=[0.0], ls='--'color='red'

最后,我們可以將搜索找到的候選解的序列繪制成黑點。 

  1. # plot the sample as black circles  
  2. pyplot.plot(solutions, [objective(x) for x in solutions], 'o', color='black'

結合在一起,下面列出了在目標函數的響應面上繪制改進解序列的完整示例。 

  1. # hill climbing search of a one-dimensional objective function  
  2. from numpy import asarray  
  3. from numpy import arange  
  4. from numpy.random import randn  
  5. from numpy.random import rand  
  6. from numpy.random import seed  
  7. from matplotlib import pyplot  
  8. # objective function  
  9. def objective(x):  
  10.  return x[0]**2.0  
  11. # hill climbing local search algorithm  
  12. def hillclimbing(objective, bounds, n_iterations, step_size):  
  13.  # generate an initial point  
  14.  solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])  
  15.  # evaluate the initial point  
  16.  solution_eval = objective(solution)  
  17.  # run the hill climb  
  18.  solutions = list()  
  19.  solutions.append(solution)  
  20.  for i in range(n_iterations):  
  21.   # take a step  
  22.   candidate = solution + randn(len(bounds)) * step_size  
  23.   # evaluate candidate point  
  24.   candidte_eval = objective(candidate)  
  25.   # check if we should keep the new point  
  26.   if candidte_eval <= solution_eval:  
  27.    # store the new point  
  28.    solution, solution_eval = candidate, candidte_eval  
  29.    # keep track of solutions  
  30.    solutions.append(solution) 
  31.     # report progress  
  32.    print('>%d f(%s) = %.5f' % (i, solution, solution_eval))  
  33.  return [solution, solution_eval, solutions]  
  34. # seed the pseudorandom number generator  
  35. seed(5)  
  36. # define range for input  
  37. bounds = asarray([[-5.0, 5.0]])  
  38. # define the total iterations  
  39. n_iterations = 1000  
  40. # define the maximum step size  
  41. step_size = 0.1  
  42. # perform the hill climbing search  
  43. best, score, solutions = hillclimbing(objective, bounds, n_iterations, step_size)  
  44. print('Done!')  
  45. print('f(%s) = %f' % (best, score))  
  46. # sample input range uniformly at 0.1 increments  
  47. inputs = arange(bounds[0,0], bounds[0,1], 0.1)  
  48. # create a line plot of input vs result 
  49. pyplot.plot(inputs, [objective([x]) for x in inputs], '--')  
  50. # draw a vertical line at the optimal input  
  51. pyplot.axvline(x=[0.0], ls='--'color='red' 
  52. # plot the sample as black circles  
  53. pyplot.plot(solutions, [objective(x) for x in solutions], 'o', color='black' 
  54. pyplot.show() 

運行示例將執行爬山搜索,并像以前一樣報告結果。像以前一樣創建一個響應面圖,顯示函數的熟悉的碗形,并用垂直的紅線標記函數的最佳狀態。在搜索過程中找到的最佳解決方案的順序顯示為黑點,沿著碗形延伸到最佳狀態。

 

 

責任編輯:龐桂玉 來源: Python中文社區 (ID:python-china)
相關推薦

2021-03-23 15:35:36

Adam優化語言

2020-12-17 10:00:16

Python協程線程

2021-03-12 09:45:00

Python關聯規則算法

2023-10-07 13:13:24

機器學習模型數據

2020-12-07 11:23:32

Scrapy爬蟲Python

2017-01-10 09:07:53

tcpdumpGET請求

2020-12-01 12:44:44

PythonHook鉤子函數

2020-10-27 10:43:24

Redis字符串數據庫

2020-11-24 11:50:52

Python文件代碼

2021-06-07 09:51:22

原型模式序列化

2009-11-17 14:50:50

Oracle調優

2018-01-30 05:04:06

2021-04-19 23:29:44

MakefilemacOSLinux

2012-06-28 10:26:51

Silverlight

2025-01-24 08:38:47

2020-09-11 09:35:18

前端JavaScript策略模式

2021-04-27 10:16:51

優化機器學習人工智能

2019-07-24 15:29:55

JavaScript開發 技巧

2009-11-05 10:55:22

Visual Stud

2021-01-11 09:33:37

Maven數目項目
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 日韩电影一区二区三区 | 日本精品一区二区三区视频 | 精品国产黄a∨片高清在线 成人区精品一区二区婷婷 日本一区二区视频 | 久久精品一区二 | 精品一二三 | 久久69精品久久久久久久电影好 | 亚洲精品久久久久国产 | 91精品国产91久久久久久 | 成人在线一区二区三区 | 一区二区三区亚洲 | 亚洲一区二区三区视频 | 国产91精品久久久久久久网曝门 | 亚洲欧美日韩电影 | 国产高清在线精品 | 99久久婷婷国产综合精品电影 | 在线播放中文字幕 | 99久久久99久久国产片鸭王 | 欧美日韩三级在线观看 | 啪一啪在线视频 | a在线视频| 亚洲性爰 | 国产精品日产欧美久久久久 | 91久久精品一区 | 久久国产精品-国产精品 | 久久国产精品一区二区三区 | av免费看在线 | 欧美精品在线一区二区三区 | 午夜一区二区三区 | www日韩高清 | jizz在线看片 | 国产福利在线播放麻豆 | 99精品免费视频 | 日日操视频 | 国产精品永久久久久久久www | 亚洲精品久久久久中文字幕欢迎你 | 成人高清在线视频 | 国产精品中文字幕在线播放 | 国产精品色哟哟网站 | 超碰导航| 欧美在线观看免费观看视频 | 久久久久久国产精品免费免费狐狸 |