如何使用simanneal包

时间:2017-04-26 21:57:21

标签: python-3.x simulated-annealing

我正在尝试通过simanneal包https://github.com/perrygeo/simanneal使用模拟退火来优化我的函数/对象的参数。 我的代码如下:

from simanneal import Annealer

class ReservoirAnnealer(Annealer):

    def __init__(self, state, res):
        self.reservoir = res
        self.resSize = np.size(self.reservoir.W_top)
        super(ReservoirAnnealer, self).__init__(state) 


    def move(self):
        a = random.randint(0, self.resSize)
        b = random.randint(0, self.resSize)
        self.state[a,b] ^= 1

    def energy(self):
        reservoir.W = self.state
        return reservoir.fit(data, 1500, penalty=5e-7, errorEvaluationLength=750)

reservoir = Reservoir(1,1023,spectralRadius=1.25,inputScaling=1,leakingRate=0.3, transientTime=100)
initialState = reservoir.W_top.ravel()
annealer = ReservoirAnnealer(initialState, reservoir)

W_top是一个内部为0或1的矩阵,所以像这样:

[ 1.  1.  1. ...,  0.  0.  1.]

当我执行上面的代码时,我收到错误:

ValueError                                Traceback (most recent call last)
<ipython-input-87-5a5b9eb8c324> in <module>()
     20 reservoir = Reservoir(1,1023,spectralRadius=1.25,inputScaling=1,leakingRate=0.3, transientTime=100)
     21 initialState = reservoir.W_top.ravel()
---> 22 annealer = ReservoirAnnealer(initialState, reservoir)
     23 #itinearay, cost = annealer.anneal()

<ipython-input-87-5a5b9eb8c324> in __init__(self, state, res)
      6         self.reservoir = res
      7         #self.resSize = np.size(self.reservoir.W)
----> 8         super(ReservoirAnnealer, self).__init__(state)
      9 
     10 

C:\Users\Luca\Anaconda3\lib\site-packages\simanneal\anneal.py in __init__(self, initial_state, load_state)
     45 
     46     def __init__(self, initial_state=None, load_state=None):
---> 47         if initial_state:
     48             self.state = self.copy_state(initial_state)
     49         elif load_state:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我真的不知道,这意味着什么。原始示例使用字典,但我的矩阵非常大,我不想把它放在字典中。 有人知道如何正确使用图书馆吗?

1 个答案:

答案 0 :(得分:2)

将列表传递给它。由于numpy数组@ line anneal上的if语句,它失败了:47