Skip to content Skip to sidebar Skip to footer

Select An Item From A List Of Object Of Any Type When Using Tensorflow 2.x

Given a list of instances of class A, [A() for _ in range(5)], I want to randomly select one of them (see the following code for an example) class A: def __init__(self, a):

Solution 1:

I'm working on the same thing at the moment. Here's what I've got so far. If anyone knows a better way I'd be interested to hear it too. When I run it on an expensive call it is appropriately faster than if I compute and return all of the values.

@tf.function
def f2():
    a_list = [A(i) for i inrange(5)]
    idx = tf.cast(tf.random.uniform(shape=[], maxval=4), tf.int32)
    return tf.switch_case(idx, a_list)

For a speed comparison I made the call method of A expensive matrix algebra. Then consider an alternate function which invokes every function:

@tf.function
def f3():
    a_list = [A(i) for i inrange(40)]
    results = [a() for a in a_list]
    return results

Running f2 with 40 elements: 0.42643 seconds

Running f3 with 40 elements: 14.9153 seconds

So that looks to be right about exactly the expected 40x speedup for only choosing one branch.

Post a Comment for "Select An Item From A List Of Object Of Any Type When Using Tensorflow 2.x"