简体   繁体   中英

How to access Tensor values in eager mode

I use the map function on a Dataset of mine. Within the function that is mapped, i want to access the values of the Tensor to use it in an "if" for example.

But i see now way to access a Tensor at all.

Im in eager mode and have tensorflow 2.1 (since anaconda doesnt support any newer version).

Here is a simple example code of what i mean:

def f1(C):
    print("every numba")
    #Access C somehow
    #if C < 2:
    #   C = C-1
    return C+2

dataset = tf.data.Dataset.range(1, 6)  # ==> [ 1, 2, 3, 4, 5 ]
dataset2 = dataset.map(f1)

I guess that an approach like this could work for you.

def f1(C):
    print("print ", C)
    if C < 2:
       C = C-1
    return C

dataset = tf.data.Dataset.range(1, 6)  # ==> [ 1, 2, 3, 4, 5 ]
dataset = dataset.map( lambda x: tf.py_function(
                                    f1,
                                    inp=[x], Tout=tf.int64))
for x in dataset:
    print(x)

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