【问题标题】:keras model with one connection per input node每个输入节点一个连接的 keras 模型
【发布时间】:2020-06-03 13:55:52
【问题描述】:

我想在 keras 中创建一个顺序模型,其中一个隐藏层的节点数与输入节点数一样多。每个输入节点应该只连接到一个隐藏节点。隐藏层中的所有节点都应连接到单个输出节点:as in this image

我希望能够指定隐藏层的激活函数。

是否可以在 keras 中使用 Sequential() 模型来实现?

【问题讨论】:

    标签: keras layer


    【解决方案1】:

    这是一个自定义层,您可以在其中做任何您想做的事情:

    import keras
    import tensorflow as tf
    from keras.layers import *
    from keras import Sequential
    import numpy as np
    
    tf.set_random_seed(10)
    
    class MyDenseLayer(keras.layers.Layer):
      def __init__(self):
        super(MyDenseLayer, self).__init__()
    
      def parametric_relu(self, _x):
        # some more or less complicated activation
        # with own weight
        pos = tf.nn.relu(_x)
        neg = self.alphas * (_x - abs(_x)) * 0.5
        return pos + neg
    
      def build(self, input_shape):
        # main weight
        self.kernel = self.add_weight("kernel",
                                      shape=[int(input_shape[-1]),],
                                      initializer=tf.random_normal_initializer())
        # any additional weights here
        self.alphas = self.add_weight('alpha', shape=[int(input_shape[-1]),],
                            initializer=tf.constant_initializer(0.0),
                                dtype=tf.float32)
        self.size = int(input_shape[-1])
    
      def call(self, input):
        linear = tf.matmul(input, self.kernel*tf.eye(self.size))
        nonlinear = self.parametric_relu(linear)
        return nonlinear
    
    
    model = Sequential()
    model.add(MyDenseLayer())
    model.build((None, 4))
    
    print(model.summary())
    x = np.ones((5,4))
    print(model.predict(x))
    

    【讨论】:

      猜你喜欢
      • 2018-05-20
      • 2020-08-10
      • 2019-03-31
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      相关资源
      最近更新 更多