How can I make this piece of code even faster?
auriocus at gmx.de
Sun Jul 21 09:24:25 CEST 2013
How about using numpy?
Am 20.07.13 22:22, schrieb pablobarhamalzas at gmail.com:
> Ok, I'm working on a predator/prey simulation, which evolve using genetic algorithms. At the moment, they use a quite simple feed-forward neural network, which can change size over time. Each brain "tick" is performed by the following function (inside the Brain class):
> count = -1
> for x in range(hidden_num):
> temp = 0
> for y in range(input_num):
> count += 1
> temp += inputs[y] * h_weight[count]
> hidden[x] = 1/(1+e**(-temp))
I don't really understand this loop, but it looks to me like a
matrix-vector multiplication of the matrix of weights (indexed with a
single continous index) with the inputs.
Given that you reshape the weights() array correctly into a
hidden_num-by-input_num array, this would result in
import numpy as np
hidden = 1.0/(1.0 + np.exp(-np.dot(h_weights, inputs)))
The matrix-vector product is then executed by a compiled loop. You can
reshape your existing lists into that form by
inputs = np.array(inputs)
h_weight = np.reshape(h_weight, (hidden_num, input_num))
... but of course you should use this only to check whether you get the
correct result. You don't want to do that in the loop, instead, store
the weights always in matrix form.
More information about the Python-list