【问题标题】:Tensorflow Get a Number of a TensorTensorflow 获取一个张量的数量
【发布时间】:2021-04-01 05:27:49
【问题描述】:

我有一个随机搜索问题。我需要超参数。

z_mean = Dense(units=hp.Int('unitsBottle',min_value=8,max_value=48,step=8))(h)
latentVariable = hp.get('unitsBottle')
z_log_var = Dense(units=latentVariable)(h)

latentVariable 是一个张量。我可以打印它:

tf.Tensor(16, shape=(), dtype=int32)

但我需要数字 16。而不是张量。作为一个整数(标量),这样我就可以把它放进去

z = Lambda(sampling, 
            output_shape=(latenteVariable,))([z_mean, 
            z_log_var, latenteVariable])

我怎样才能只得到号码?

【问题讨论】:

    标签: python tensorflow tensor


    【解决方案1】:

    就像在张量上调用int()一样简单:

    >>> tensor = tf.constant(16)
    >>> print(tensor)
    tf.Tensor(16, shape=(), dtype=int32)
    
    >>> int(tensor)
    16
    
    >>> tensor.numpy()
    16
    >>> print(type(tensor.numpy()))
    <class 'numpy.int32'>
    

    【讨论】:

    • 谢谢。我希望这是问题所在。问题一定出在其他地方。
    • @user8020627 有什么问题?
    • 难度更大。我必须提出一个新问题。由于未知原因,选择全局变量会导致 3 层.. 选择局部变量会导致 TensorFlow 中的 8 层。
    • 那么,请接受 Ynjxsjmh 的回答作为关闭此问题的正确答案。
    【解决方案2】:

    @Ynjxsjmh 所述,使用.numpy() 更直观。但是,我们也可以在张量上使用eval 来获取值。

    from tensorflow.keras.backend import eval 
    
    one = tf.constant(8)
    two = tf.constant(8)
    product = tf.add(one, two)
    
    eval(one), eval(two), eval(product)
    (8, 8, 16)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 2020-06-22
      相关资源
      最近更新 更多