首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >keras模型,每个输入节点有一个连接

keras模型,每个输入节点有一个连接
EN

Stack Overflow用户
提问于 2020-06-03 21:55:52
回答 1查看 255关注 0票数 0

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

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

在keras中使用Sequential()模型可以实现这一点吗?

EN

回答 1

Stack Overflow用户

发布于 2020-06-04 06:12:00

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

代码语言:javascript
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62174654

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档