3

Hi I'm a newbie to Tensorflow. What I want to do is something like this in R:

mat = tf$Variable(matrix(1:4, nrow = 2))
apply(mat, 1, cumprod)

Is this do-able in Tensorflow, either in Python API or R tensorflow package? Thanks!

EDIT: tf$cumprod is actually what I want.

Spacedman
  • 92,590
  • 12
  • 140
  • 224
Miller Zhu
  • 697
  • 1
  • 7
  • 15

1 Answers1

7

The TensorFlow Python API includes the tf.map_fn(fn, elems) higher-order operator, which allows you to specify a (Python) function fn that will be applied to each slice of elems in the 0th dimension (i.e. to each row if elems is a matrix).

Note that, while tf.map_fn() is very general, it may be more efficient to use specialized ops that either broadcast their arguments on one or more dimensions (e.g. tf.multiply()), or reduce in parallel across one or more dimensions (e.g. tf.reduce_sum()). However, tf.map_fn() is useful when there is no built-in operator to do what you want.

Duloren
  • 2,395
  • 1
  • 25
  • 36
mrry
  • 125,488
  • 26
  • 399
  • 400
  • Thanks for the answer, I have a problem here, when I set the entropy from scipy as the argument it raises an error. Is it obligatory to not call any function of a library? – sariii May 25 '19 at 16:37
  • Thank you for your answer. I which to generalize this problem into something more specific (map a function on all the depth channel associated with every pixel). Could you help me, please? I asked my question in here: https://stackoverflow.com/questions/59094897/map-function-on-each-pixel-of-a-3d-tensor Thanks a lot :) – gab Nov 29 '19 at 10:45
  • It would have been nice to provide the code that actually solves the OP's question regardless of efficiency considerations. – Marius Hofert Feb 14 '21 at 02:10