模擬退火算法


一. 爬山算法 ( Hill Climbing )

      作為對比,先介紹爬山算法。爬山算法是一種簡單的貪心搜索算法,該算法每次從當前解的臨近解空間中選擇一個最優解作為當前解,直到達到一個局部最優解。

      爬山算法實現很簡單,其主要缺點是會陷入局部最優解,而不一定能搜索到全局最優解。如圖1所示:假設C點為當前解,爬山算法搜索到A點這個局部最優解就會停止搜索,因為在A點無論向那個方向小幅度移動都不能得到更優的解。

 

二. 模擬退火(SA,Simulated Annealing)思想

      爬山法是完完全全的貪心法,每次都鼠目寸光的選擇一個當前最優解,因此只能搜索到局部的最優值。模擬退火其實也是一種貪心算法,但是它的搜索過程引入了隨機因素。模擬退火算法以一定的概率來接受一個比當前解要差的解,因此有可能會跳出這個局部的最優解,達到全局的最優解。以圖1為例,模擬退火算法在搜索到局部最優解A后,會以一定的概率接受到E的移動。也許經過幾次這樣的不是局部最優的移動后會到達D點,於是就跳出了局部最大值A。

      模擬退火算法描述:

  • 若J( Y(i+1) )>= J( Y(i) )  (即移動后得到更優解),則總是接受該移動
  • 若J( Y(i+1) )< J( Y(i) )  (即移動后的解比當前解要差),則以一定的概率接受移動,而且這個概率隨着時間推移逐漸降低(逐漸降低才能趨向穩定)

  這里的“一定的概率”的計算參考了金屬冶煉的退火過程,這也是模擬退火算法名稱的由來。

  根據熱力學的原理,在溫度為T時,出現能量差為Δt的降溫的概率為P(Δt),表示為:

    P(Δt) = e(- Δt/(kT) )

  其中k是一個常數,e表示自然指數,且Δt<0。這條公式說白了就是:溫度越高(T越大),出現一次能量差為Δt的降溫的概率就越大;溫度越低(T越小),則出現降溫的概率就越小。又由於Δt總是小於0(否則就不叫退火了),因此Δt/kT < 0 ,所以P(Δt)的函數取值范圍是(0,1) 。隨着溫度T的降低,P(Δt)會逐漸降低。

 

三. 模擬退火算法偽代碼

/*
* J(y):在狀態y時的評價函數值
* Y(i):表示當前狀態
* Y(i+1):表示新的狀態
* r: 用於控制降溫的快慢
* T: 系統的溫度,系統初始應該要處於一個高溫的狀態
* T_min :溫度的下限,若溫度T達到T_min,則停止搜索
*/
while( T > T_min )
{
  dE = J( Y(i+1) ) - J( Y(i) ) ; 

  if ( dE >=0 )                        //表達移動后得到更優解,則總是接受移動
        Y(i+1) = Y(i) ;                  //接受從Y(i)到Y(i+1)的移動
  else
  {
       if ( exp( dE/T ) > random( 0 , 1 ) )
            Y(i+1) = Y(i) ;              //接受從Y(i)到Y(i+1)的移動
  }
  T = r * T ;                          //降溫退火 ,0<r<1 。r越大,降溫越慢;r越小,降溫越快
  /*
  * 若r過大,則搜索到全局最優解的可能會較高,但搜索的過程也就較長。若r過小,則搜索的過程會很快,但最終可能會達到一個局部最優值
  */
  i ++ ;
}

 

四. 使用模擬退火算法解決旅行商問題

旅行商問題 ( TSP , Traveling Salesman Problem ) :有N個城市,要求從其中某個問題出發,唯一遍歷所有城市,再回到出發的城市,求最短的路線。
旅行商問題屬於所謂的NP完全問題,精確的解決TSP只能通過窮舉所有的路徑組合,其時間復雜度是O(N!) 。
使用模擬退火算法可以比較快的求出TSP的一條近似最優路徑。(使用遺傳算法也是可以的)模擬退火解決TSP的思路:

  1. 產生一條新的遍歷路徑P(i+1),計算路徑P(i+1)的長度L( P(i+1) )
  2. 若L(P(i+1)) < L(P(i)),則接受P(i+1)為新的路徑,否則以模擬退火的那個概率接受P(i+1) ,然后降溫
  3. 重復步驟1,2直到滿足退出條件


產生新的遍歷路徑的方法有很多,下面列舉其中3種:

  1. 隨機選擇2個節點,交換路徑中的這2個節點的順序。
  2. 隨機選擇2個節點,將路徑中這2個節點間的節點順序逆轉。
  3. 隨機選擇3個節點m,n,k,然后將節點m與n間的節點移位到節點k后面。

參考代碼

#include <iostream>  
#include <sstream>  
#include <fstream>  
#include <string>
#include <cstring>
#include <iterator>  
#include <algorithm>  
#include <climits>  
#include <cmath>  
#include <cstdlib>  
  
using namespace std;  
  
const int nCities = 10;           //城市數量  
const double SPEED = 0.98;        //退火速度  
const int INITIAL_TEMP = 1000;    //初始溫度  
const int L = 10 * nCities;       //Markov 鏈的長度  

struct unit                             //一個解  
{  
    double length;                      //代價,總長度  
    int path[nCities];                  //路徑  
    bool operator < (const struct unit &other) const  
    {  
        return length < other.length;  
    }  
};  
unit bestone = {INT_MAX, {0} };         //最優解  

double length_table[nCities][nCities];  //distance  
 
class saTSP
{
    public:
        int init_dis();                  // create matrix to storage the Distance each city
        void SA_TSP();  
        void CalCulate_length(unit &p);  //計算長度  
        void print(unit &p);             //打印一個解  
        void getNewSolution(unit &p);    // 從鄰域中獲去一個新解  
        bool Accept(unit &bestone, unit &temp, double t);//新解以Metropolis 准則接受  
};
  
//stl 中 generate 的輔助函數對象  
class GenbyOne {  
    public:  
        GenbyOne (int _seed = -1): seed(_seed){}  
        int operator() (){return seed += 1;}  
    private:  
        int seed;  
};  
  
void saTSP::SA_TSP()  
{  
    srand((int)time(0));  
    int i = 0;  
    double r = SPEED;  
    double t = INITIAL_TEMP;  
    const double t_min = 0.001; //溫度下限,若溫度達到t_min ,則停止搜索  
  
    //choose an initial solution ~  
    unit temp;  
    generate(temp.path, temp.path + nCities, GenbyOne(0));  
    random_shuffle(temp.path, temp.path + nCities);  
    CalCulate_length(temp);  
    memcpy(&bestone, &temp, sizeof(temp));  

    // while the stop criterion is not yet satisfied do  
    while ( t > t_min )  
    {  
        for (i = 0; i < L; i++)   
        {  
  
            getNewSolution(temp);  
            //cout << "dkkd:" << bestone.length << endl;
            if(Accept(bestone,temp, t))  
            {  
                memcpy(&bestone, &temp, sizeof(unit));  
            }  
            else  
            {  
                memcpy(&temp, &bestone, sizeof(unit));  
            }  
        }  
        t *= r; //退火  
    }  
    return;  
}  
  
bool saTSP::Accept(unit &bestone, unit &temp, double t)  
{  
    if (bestone.length > temp.length) //獲得更短的路徑  
    {  
        return true;  
    }  
    else  
    {  
        if ((int)(exp((bestone.length - temp.length) / t) * 100) > (rand() % 101) )   
        {  
            return true;  
        }  
    }  
    return false;  
}  
  
void saTSP::getNewSolution(unit &p)  
{  
    int i = rand() % nCities;  
    int j = rand() % nCities;  
    if (i > j)   
    {  
        int t = i;  
        i = j;  
        j = t;  
    }  
    else if (i == j)      
    {  
        return;   
    }  
  
    int choose = rand() % 3;  
    if ( choose == 0)   
    {//交換  
        int temp = p.path[i];  
        p.path[i] = p.path[j];  
        p.path[j] = temp;  
    }  
    else if (choose == 1)   
    {//置逆  
        reverse(p.path + i, p.path + j);       
    }  
    else  
    {//移位  
        if (j + 1 == nCities) //邊界處不處理  
        {  
            return;  
        }  
        rotate(p.path + i, p.path + j, p.path + j + 1);    
    }  
    CalCulate_length(p);  
}  
  
int saTSP::init_dis() // create matrix to storage the Distance each city  
{  
    int i = 0, j = 0;  
    string line;
    double word;
    ifstream infile("del2.txt");  
    if(!infile)
    {
        cout << "Cannot open the file" << endl;
        return 0;
    }
    
    while(getline(infile, line))
    {
        j = 0;
        istringstream instream(line);
        while(instream >> word)
        {
            length_table[i][j] = word;  
            ++j;
        }
        ++i;
    }
}  
  
void saTSP::CalCulate_length(unit &p)  
{  
    int j = 0;  
    p.length = 0;  
    for (j = 1; j < nCities; j++)   
    {  
        p.length += length_table[ p.path[j-1] ][ p.path[j] ];  
    }  
    p.length += length_table[p.path[ nCities - 1] ][ p.path[0] ];  
}  
  
void saTSP::print( unit &p)  
{  
    int i;  
    cout << "代價是:" << p.length << endl;  
    cout << "路徑是:";  
    for (i = 0; i < nCities; i++)   
    {  
        cout << p.path[i] << " ";  
    }  
    cout << endl;  
}  

int main(int argc, char* argv[])  
{  
    saTSP sa;
    sa.init_dis();  
    sa.SA_TSP();  
    sa.CalCulate_length(bestone);  
    sa.print(bestone);  
    return 0;  
}  

del2.txt

0 5 1272 2567 1653 2097 1425 1177 3947 3
5 0 4 2511 1633 2077 1369 1157 3961 1518
1272 4 0 1 380 1490 821 856 3660 385
2567 2511 1 0 1 2335 1562 2165 3995 933
1653 1633 380 1 0 1 1041 1135 3870 456
2097 2077 1490 2335 1 0 1 920 2170 1920
1425 1369 821 1562 1041 1 0 1 4290 626
1177 1157 856 2165 1135 920 1 0 1 1290
3947 3961 3660 3995 3870 2170 4290 1 0 4
3 1518 385 993 456 1920 626 1290 4 0

運行結果

 

 

參考

 大白話解析模擬退火算法

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM