Reputation:
I am aware how the yield
keyword is used in python to return the generators some thing like this
def example_function():
for i in xrange(1, 10)
yield i
But I have code like this
def feed_forward(self,inputs):
activations = [inputs]
for I in xrange(len(self.weights)):
activation = activations[i].dot(self.weights[i])
activations.append(activation)
return activations
Where the list going to be created is itself required in the iteration inside the function.
How do I rewrite the code to more pythonic code, by using the yield
keyword?
Upvotes: 0
Views: 39
Reputation: 1125028
Replace .append()
calls and the initial list definition with yield
statements. You are using the preceding result each time in the next iteration of the loop, simply record the last 'activation' and re-use that:
def feed_forward(self, inputs):
yield inputs
activation = inputs
for weight in self.weights:
activation = activation.dot(weight)
yield activation
Upvotes: 2