首页 > 解决方案 > 每个输入节点一个连接的 keras 模型

问题描述

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

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

是否可以使用 keras 中的 Sequential() 模型来实现这一点?

标签: keraslayer

解决方案


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

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))

推荐阅读