【问题标题】:Numpy-like indexing and assignment with Tensorflow使用 Tensorflow 进行类似 Numpy 的索引和赋值
【发布时间】:2020-12-15 12:42:48
【问题描述】:

我做了一个简单的 numpy 数组索引和赋值示例,目标是在黑屏上制作一个小的白色方块。 如何使用 Tensorflow 复制以下代码?

black_img = np.zeros([5, 5, 3])
white_rect = np.ones([3, 3])
size = np.arange(3)

black_img[size, size] = white_rect

【问题讨论】:

    标签: python arrays numpy tensorflow indexing


    【解决方案1】:

    您可以在 TensorFlow 中创建常量或变量。

    black_img = np.zeros([5, 5, 3], dtype = np.int32)
    black_img_tf = tf.constant(np.zeros([5, 5, 3], dtype = np.int32))
    

    输出:

    <tf.Tensor: shape=(5, 5, 3), dtype=int32, numpy=
    array([[[0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0]],
    
           [[0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0]],
    
           [[0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0]],
    
           [[0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0]],
    
           [[0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0]]])>
    

    但是,TensorFlow 不支持像 NumPy 那样的项目分配。 但是,您可以使用从 NumPy 操作获得的结果创建新的常量或变量。

    代码:

    black_img[size, size] = white_rect
    tf.constant(black_img)
    

    输出:

    <tf.Tensor: shape=(5, 5, 3), dtype=int32, numpy=
    array([[[1, 1, 1],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0]],
    
           [[0, 0, 0],
            [1, 1, 1],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0]],
    
           [[0, 0, 0],
            [0, 0, 0],
            [1, 1, 1],
            [0, 0, 0],
            [0, 0, 0]],
    
           [[0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0]],
    
           [[0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0]]])>
    

    请注意,不允许单独分配项目,但您可以对张量进行加法、减法等操作。

    c = tf.constant(np.ones([3, 3], dtype = np.int32)) + tf.constant(np.ones([3, 3], dtype = np.int32))
    c
    

    输出:

    <tf.Tensor: shape=(3, 3), dtype=int32, numpy=
    array([[2, 2, 2],
           [2, 2, 2],
           [2, 2, 2]])>
    

    【讨论】:

    • 所以你的意思是这是不可能的,我最好的选择是使用 numpy 并转换回 TensorFlow?
    • Tensorflow 不支持赋值。如果您尝试进行值分配,它只会引发类型错误。通过执行 tensorflow 支持的其他操作,您始终可以得到想要的结果。检查thisthis 以供参考。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 2021-01-29
    • 2012-07-08
    • 2020-04-28
    • 2014-01-08
    • 2018-02-17
    相关资源
    最近更新 更多