keras多项式特征层

时间:2019-06-08 21:17:12

标签: tensorflow machine-learning keras keras-layer

我想拥有一个可以创建乘以X.T * X的多项式特征的图层:

class QuadraticLayer(Layer):

def __init__(self, **kwargs):
    super(QuadraticLayer, self).__init__(**kwargs)

def build(self, input_shape):
    assert isinstance(input_shape, tuple)
    print(input_shape)
    self.in_shape = input_shape[1]
    self.out_shape = input_shape[1] ** 2
    super(QuadraticLayer, self).build(input_shape)  # Be sure to call this at the end

def call(self, x):
    print(x.shape)
    tf.reshape(x, (self.in_shape, 1, -1), name=None)
    x = tf.matmul(x, x, transpose_a=True)
    return tf.reshape(x, (-1, self.out_shape))

def compute_output_shape(self, input_shape):
    return (None, self.out_shape)

我的问题是在call张量x中是一个批处理张量-如何编写将在每个训练示例中工作的层而不是在整个批处理张量上工作的层?

1 个答案:

答案 0 :(得分:0)

这是一个主意:

def call(self, x):
    x = K.backend.batch_dot(tf.reshape(x, (-1, 1, self.in_shape)), tf.reshape(x, (-1, self.in_shape, 1)), axes=[1,2])
    return tf.reshape(x, (-1, self.out_shape))

但是有没有更好的解决方案?