【问题标题】:how to manipulate tensor array, 'Tensor' object does not support item assignment如何操作张量数组,“张量”对象不支持项目分配
【发布时间】:2023-03-18 00:55:01
【问题描述】:

我需要如下操作张量

ary = np.array([82.20674918566776, 147.55325947521865, 25.804872964169384, 85.34690767735665, 1, 0]).reshape(1,1,1,1,6)

tf_array = tf.convert_to_tensor(ary, tf.float32)
value_x = 13.0
norm_value = 416.0

tf_array[...,0:4] = tf_array[...,0:4] * (value_x / norm_value)

执行时

TypeError: 'Tensor' 对象不支持项目分配

【问题讨论】:

    标签: python-3.x tensorflow


    【解决方案1】:

    您不能在 TensorFlow 中赋值,因为张量是不可变的(TensorFlow 变量的值可以更改,但这更像是用新张量替换它们的内部张量)。在 TensorFlow 中最接近项目分配的可能是 tf.tensor_scatter_nd_update,它仍然没有分配新值,而是创建一个新的张量并替换了一些值。一般来说,您必须找到从您拥有的张量中计算所需结果的方法。在您的情况下,您可以这样做:

    import tensorflow as tf
    import numpy as np
    
    ary = np.array([82.20674918566776, 147.55325947521865,
                    25.804872964169384, 85.34690767735665,
                    1, 0]).reshape(1,1,1,1,6)
    tf_array = tf.convert_to_tensor(ary, tf.float32)
    value_x = 13.0
    norm_value = 416.0
    
    # Mask for the first four elements in the last dimension
    m = tf.range(tf.shape(tf_array)[0]) < 4
    # Pick the multiplication factor where the mask is true and 1 everywhere else
    f = tf.where(m, value_x / norm_value, 1)
    # Multiply the tensor
    tf_array_multiplied = tf_array * f
    # [[[[[2.568961   4.611039   0.80640227 2.667091   0.03125    0.        ]]]]]
    

    【讨论】:

      【解决方案2】:

      谢谢,

      我尝试了解决方法

      ary = np.array([82.20674918566776, 147.55325947521865, 25.804872964169384, 85.34690767735665, 1, 0]).reshape(1,1,1,1,6)
      
      tf_array = tf.convert_to_tensor(ary, tf.float32)
      value_x = 13.0
      norm_value = 416.0
      
      #create array of same shape and values to be multiplied with
      temp = np.array([value_x /norm_value , value_x /norm_value, value_x /norm_value, value_x /norm_value, 1, 1]).reshape(1,1,1,1,6)
      
      #convert numpy array to tensorflow tensor
      normalise_ary = tf.convert_to_tensor(temp, tf.float32)
      
      tf_array = tf_array * normalise_ary
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-08
        • 1970-01-01
        • 2022-08-19
        • 2020-10-06
        • 1970-01-01
        • 2020-11-19
        • 2019-05-07
        相关资源
        最近更新 更多