【问题标题】:tensorflow map function not being invoked未调用张量流映射函数
【发布时间】:2018-09-19 04:11:07
【问题描述】:

根据我对 tensorflow 中 map 函数的理解,我预计 my_map 会被调用 60,000 次,但它只被调用了一次。

输出

使用 TensorFlow 后端。 (60000, 28, 28) Tensor("map/while/TensorArrayReadV3:0", shape=(28, 28), dtype=uint8)

进程以退出代码 0 结束

代码:

import tensorflow as tf
from keras.datasets import mnist

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()


def my_map(elem):
    print(elem)
    return elem


print(train_images.shape)

tf_map = tf.map_fn(fn=my_map, elems=train_images)


with tf.Session() as sess:
    sess.run(tf_map)

我做错了什么?任何帮助,将不胜感激。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    my_map 中的打印不能用于打印。请测试一下:

    import tensorflow as tf
    from keras.datasets import mnist
    
    (train_images, train_labels), (test_images, test_labels) = mnist.load_data()
    
    
    def my_map(elem):
        #print(elem)
        elem = elem + 1
        return elem
    
    
    print(train_images.shape)
    
    tf_map = tf.map_fn(fn=my_map, elems=train_images)
    
    
    with tf.Session() as sess:
        print(sess.run(tf_map[0,0]))
    

    【讨论】:

    • 你是对的。对不起,我的错,我检查了一些变量,因为它们中的大多数都是零,我认为它不起作用。感谢您的帮助!
    【解决方案2】:

    根据下面对map_fn的描述。 (https://www.tensorflow.org/api_docs/python/tf/map_fn)

    “map_fn”返回由参数“fn”中的函数操作的张量。 在您的情况下, train_images 第一维数是 6,000。 “map_fn”应用 my_map 函数 6,000 次并返回结果。这就是你刚刚看到结果 1 行的原因。

    您可以检查它,只需打印 tf_map.shape 以供您确认。

    当您需要打印结果时,请执行以下操作:

    with tf.Session() as sess:
        print(sess.run(tf_map))
    

    【讨论】:

    • 如果 my_map 已经应用了 60,000,为什么我没有看到 60,000 print(elem)。这就是困扰我的问题。还是谢谢。
    • 我认为“map_fn”是海量数据操作的实用程序。您可以参考我的新以下代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    相关资源
    最近更新 更多