0

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

5 Comments

@Goutam: ah, of course. It's the previous value, really. I'll correct.
Is it possible return generators in reverse order?
@Goutam: no; generators are a way of writing iterators, and iterators go one way. The only option is to capture all output in a list, then reversing the list.
Is it pythonic to do that?
@Goutam: What problem are you trying to solve? Can you not just produce the results in reverse order?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.