keras - 每个输入节点一个连接的 keras 模型
问题描述
我想在 keras 中创建一个顺序模型,其中一个隐藏层的节点数与输入节点数一样多。每个输入节点应该只连接到一个隐藏节点。隐藏层中的所有节点都应连接到单个输出节点:如图所示
我希望能够指定隐藏层的激活函数。
是否可以使用 keras 中的 Sequential() 模型来实现这一点?
解决方案
这是一个自定义层,您可以在其中做任何您想做的事情:
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))
推荐阅读
- python - 如何从数据格式中创建日期年月日1日2日3日4……日31
- node.js - node.js 中的全局模块
- symfony - 具有 MEMBER OF 和空参数的 Doctrine querybuilder
- typescript - 打字稿在其键之一中从对象推断信息
- android-fragments - 如何将自定义侦听器从 Fragment 传递到 MVVM 中的 VM?
- python - 将大文件传递给 Celery 进行处理不起作用
- javascript - stripe.redirectToCheckout:您必须提供 lineItems、items 或 sessionId 之一
- winforms - 如何在 Rider ide 2020.1.2 中刷新 Winforms 自定义控件
- c - 如何改进 strspn 的实现
- intellij-idea - 在 PhpStorm/IntelliJ 中替换/封装文本的宏?