Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow apply op to each element of a 2d tensor

Tags:

tensorflow

What I'm after is the ability to apply a tensorflow op to each element of a 2d tensor e.g.

input = tf.Variable([[1.0, 2.0], [3.0, 4.0])
myCustomOp = ... # some kind of custom op that operates on 1D tensors
finalResult = tf.[thing I'm after](input, myCustomOp)
# when run final result should look like: [myCustomOp([1.0, 2.0]), myCustomOp([3.0, 4.0)]

Any ideas?

like image 850
Daniel Slater Avatar asked Mar 27 '16 20:03

Daniel Slater


People also ask

How do you access the element in a tensor?

To access elements from a 3-D tensor Slicing can be used. Slicing means selecting the elements present in the tensor by using “:” slice operator. We can slice the elements by using the index of that particular element.

Can you slice tensors?

You can use tf. slice on higher dimensional tensors as well. You can also use tf. strided_slice to extract slices of tensors by 'striding' over the tensor dimensions.

Is it possible to create a tensor with elements of different data types?

Data TypesIt is not possible to have a Tensor with more than one data type.

What does tf Map_fn do?

map_fn also supports functions with multi-arity inputs and outputs: If elems is a tuple (or nested structure) of tensors, then those tensors must all have the same outer-dimension size ( num_elems ); and fn is used to transform each tuple (or structure) of corresponding slices from elems .


1 Answers

The next version of TensorFlow (0.8, which is currently available if you build from source or download a nightly build) includes higher-order operators including tf.map_fn() and tf.scan() that allow you to apply a function made up of TensorFlow ops to subtensors of a larger tensor.

The tf.map_fn(fn, elems, ...) function unpacks the N-dimensional input elems along the first dimension into multiple N-1-dimensional subtensors and applies fn to each subtensor. This seems to fit your use case perfectly:

input = tf.Variable([[1.0, 2.0], [3.0, 4.0]])
function_to_map = lambda x: f(x)  # Where `f` instantiates myCustomOp.
final_result = tf.map_fn(function_to_map, input)
like image 167
mrry Avatar answered Sep 18 '22 08:09

mrry