keras中的简单自定义层,张量流混乱

时间:2019-09-25 16:25:52

标签: tensorflow keras complex-numbers

首先,在我解释之前,这是相关的代码段:

input = Input(shape=(784, ))
hidden1 = Dense(784, activation='relu')(input)
hidden2 = Dense(784, activation='relu')(hidden1)
hidden3 = Dense(1568, activation='relu')(hidden2)
hidden4 = Lambda(lambda x: makeComplex(x))(hidden3)
hidden5 = Reshape((1, 28, 28))(hidden4)
hidden6 = Lambda(lambda x: ifft2(x))(hidden5)
hidden7 = Flatten()(hidden6)
output = Dense(train_targets.shape[1], activation='linear')(hidden7)
model = Model(inputs=input, outputs=output)
print(model.summary())

ifft2(x)是

def ifft2(x):
    import tensorflow as tf
    return tf.cast(tf.spectral.ifft2d(tf.cast(x,dtype=tf.complex64)),tf.float32)

我现在的目标是实现makeComplex方法。

基本上,它得到一个大小为1568的向量,我希望它以以下非常简单的方式返回大小为784的向量:

new[k] = old[k] + old[k + 1] * i,其中i是虚数单位

这是我的尝试:

def makeComplex(x):
    y = np.zeros((1, 784))
    for i in range(784):
        y[i] = np.complex(x[i], x[i + 1])
    return y

当然这不起作用,因为x实际上不是矢量,而是张量流张量。我一无所知。我该如何工作?

1 个答案:

答案 0 :(得分:0)

张量[1.,2.,3.,4。]的示例,您想要的是[1. + 2.j,3。+ 4.j]。我认为您可以使用tf.gather得到两个张量[1.,2.][3.,4.],然后使用tf.complex得到答案。

import tensorflow as tf
import numpy as np

a = tf.constant([1.,2.,3.,4.])
real = tf.gather(a,np.arange(0,a.get_shape().as_list()[0],2)) 
imag = tf.gather(a,np.arange(1,a.get_shape().as_list()[0],2))

res = tf.complex(real, imag)