Python 生成随机复数张量

Python 生成随机复数张量,python,numpy,tensorflow,Python,Numpy,Tensorflow,我需要生成一个随机向量,如下所示: Y = (np.random.randn(tf.size(signal)) + 1j * np.random.randn(tf.size(signal))) 其中变量信号是表示神经网络输出的向量,但我得到的误差如下: File "mtrand.pyx", line 1422, in mtrand.RandomState.randn File "mtrand.pyx", line 1552, in mtrand.

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

Y = (np.random.randn(tf.size(signal)) + 1j * np.random.randn(tf.size(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
,但也出现了相同的错误。

TF1.x和TF2.x:在TensorFlow中执行该操作 使用tensorflow的tensor时,应主要使用
tf
API。在您的情况下,您可以简单地使用:

Y = tf.complex(tf.random.normal((tf.size(signal),)), tf.random.normal((tf.size(signal),)))
这将返回一个随机的
复数64
张量,其实部和虚部遵循正态分布

TF2.x:急切执行 如果需要直接使用numpy,可以使用
numpy
方法在急切执行中评估张量:

Y = (np.random.randn(tf.size(signal).numpy()) + 1j * np.random.randn(tf.size(signal).numpy()))
TF1.x:使用
tf.Session
实际上,您需要在
tf.Session
中计算张量,以便通过调用以下命令获得numpy数组的输出:

注意:可能最好在会话中评估
信号
,然后使用numpy继续其余的计算(使用
signal.size
而不是
tf.size(signal)



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

我需要直接使用numpy,但是当我使用您的第二个建议时,我得到了一个错误
AttributeError:“Tensor”对象没有属性“numpy”
,当我尝试使用
tf.enable\u eager\u execution()
,它给了我另一个错误
raiseruntimeerror(“tf.placeholder()与”RuntimeError:tf.placeholder()不兼容)与急切执行不兼容。你使用的是tf 1.x,对吗?你能在问题中添加信号的定义吗?是的,我使用的是tensorflow 1.15。你的定义是什么?信号是表示神经网络输出的向量。我的意思是神经网络的输出称为信号。我添加了一个exa我想您可能需要阅读一些文档来了解TensorFlow1.x是如何工作的。
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))