【问题标题】:Generating a random complex-valued tensor生成随机复值张量
【发布时间】:2021-05-11 08:43:13
【问题描述】:

我需要生成一个随机向量如下:

Y = (np.random.randn(tf.size(signal)) + 1j * np.random.randn(tf.size(signal)))

其中变量signal 是表示神经网络输出的向量,但出现如下错误:

  File "mtrand.pyx", line 1422, in mtrand.RandomState.randn
  File "mtrand.pyx", line 1552, in mtrand.RandomState.standard_normal
  File "mtrand.pyx", line 167, in mtrand.cont0_array
TypeError: 'Tensor' object cannot be interpreted as an integer

我也试过signal.shape,但也出现了同样的错误。

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    TF1.x 和 TF2.x:在 TensorFlow 中进行操作

    在使用 tensorflow 的张量时,您应该主要使用 tf API。在您的情况下,您可以简单地使用:

    Y = tf.complex(tf.random.normal((tf.size(signal),)), tf.random.normal((tf.size(signal),)))
    

    这将返回一个随机的 complex64 张量,其中实部和虚部遵循正态分布。

    TF2.x:渴望执行

    如果您需要直接使用 numpy,您可以使用 numpy 方法在 eager execution 中评估您的张量:

    Y = (np.random.randn(tf.size(signal).numpy()) + 1j * np.random.randn(tf.size(signal).numpy()))
    

    TF1.x:使用 tf.Session 评估您的张量

    您实际上需要通过调用tf.Session.run 来评估tf.Session 中的张量以将输出作为numpy 数组:

    get_size_op = tf.size(signal)
    
    with tf.Session() as sess:
        # you might need to provide a dictionary containing 
        # the values for your placeholders (feed_dict keyword argument)
        size_signal = sess.run(get_size_op)
    
    # size_signal is an integer you can use in the numpy function
    Y = (np.random.randn(size_signal) + 1j * np.random.randn(size_signal))
    

    注意:最好在会话中评估 signal 并使用 numpy 继续其余的计算(使用 signal.size 而不是 tf.size(signal)


    注意tensor.shape 的等价物是tf.shape。我使用了tf.size,因为这是您在问题中使用的。

    【讨论】:

    • 我需要直接使用 numpy,但是当我使用你的第二个建议时,我得到一个错误 AttributeError: 'Tensor' object has no attribute 'numpy',当我尝试使用 tf.enable_eager_execution() 时,它又给了我一个错误 raise RuntimeError("tf.placeholder() is not compatible with " RuntimeError: tf.placeholder() is not compatible with eager execution
    • 那么您使用的是 tf 1.x,对吗?您能否在问题中添加signal 的定义?
    • 是的,我使用的是 tensorflow 1.15。你的定义是什么意思?信号是表示神经网络输出的向量。我的意思是神经网络的输出称为信号。
    • 我添加了一个关于如何使用 TF1.x 的示例。我认为您可能需要阅读一些文档来了解 TensorFlow 1.x 的工作原理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 2017-06-12
    • 1970-01-01
    相关资源
    最近更新 更多