Created
November 12, 2013 21:53
-
-
Save Nagasaki45/7439446 to your computer and use it in GitHub Desktop.
Simplest simulated annealing algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
class Annealer(): | |
def __init__(self, step_function, energy_function): | |
self.step_function = step_function | |
self.energy_function = energy_function | |
def run( | |
self, state, temperature, room_temperature, cooling_factor | |
): | |
best_state = state | |
energy = self.energy_function(state) | |
energy_curve = [energy] # tracking convergence | |
while temperature > room_temperature: | |
new_state = self.step_function(state) | |
new_energy = self.energy_function(new_state) | |
rand = np.random.rand() | |
if np.exp(-(energy - new_energy) / temperature) > rand: | |
state = new_state | |
energy = self.energy_function(state) | |
if new_energy > energy_curve[-1]: | |
best_state = new_state | |
energy_curve.append(new_energy) | |
temperature *= cooling_factor | |
return best_state, energy_curve |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on info from
http://en.wikipedia.org/wiki/Simulated_annealing
and
http://www.theprojectspot.com/tutorial-post/simulated-annealing-algorithm-for-beginners/6