简体   繁体   English

如何在急切模式下访问张量值

[英]How to access Tensor values in eager mode

I use the map function on a Dataset of mine.我在我的数据集上使用 map 函数。 Within the function that is mapped, i want to access the values of the Tensor to use it in an "if" for example.在映射的函数中,我想访问 Tensor 的值以在“if”中使用它。

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).我处于急切模式并且拥有 tensorflow 2.1(因为 anaconda 不支持任何更新版本)。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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