简体   繁体   中英

TensorFlow apply a function to each row of a matrix variable

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.

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 (ie 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 (eg tf.multiply() ), or reduce in parallel across one or more dimensions (eg tf.reduce_sum() ). However, tf.map_fn() is useful when there is no built-in operator to do what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM