04 keras写自己的层

编写自己的神经层

"""
编写自己的keras层只需要实现3个方法以及一个初始化方法,写的时候可以参阅相关的源代码,一般不需要自定义神经层
1. build(input_shape): 定义权重的地方。这个方法必须设置`self.built =True`,通过调用super来完成
2. call(inputs): 这里是运算部分,只需要关注传入call的第一个参数:输入张量
3. compute_output_shape(input_shape):  如果输入与输出的shape不一致,这里应该定义shaoe变化的逻辑,折让keras能够自动推断各层的形状
"""
from keras import backend as K
from keras.engine.topology import Layer
import numpy as np


class MyLayer(Layer):  # 继承自Layer

    # 1. 重写初始化方法,增加了output_dim
    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
        # 因为重写了init方法,因此需要调用父类的方法
        super().__init__(**kwargs)

    # 2. 重写build方法,主要是定义权重.也就是self.kernel
    def build(self, input_shape):
        self.kernel = self.add_weight(name='kernel',
                                      shape=(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True)
        # 这个方法必须设置`self.built=True',继承父类方法即可
        super().build(input_shape)

    # call和compute方法都不建议使用self绑定,因为可能会重名
    # 3. call(x) 主要是运算部分,只需要传入inputs,返回运算结果
    def call(self, inputs):
        return K.dot(inputs, self.kernel)  # 返回运算结果

    # 4. 如果输入与输出的shape不一致,这里应该定义shaoe变化的逻辑,折让keras能够自动推断各层的形状
    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.output_dim)

实例

import keras
from keras.layers import Layer, Dense, Dropout, Activation
from keras import backend as K
# -------------> 前半部分是重写函数需要用到的
from keras.models import Sequential
from keras.datasets import mnist


class Antirectifier(Layer):
    """
    # 1.因为不需要传入额外的东西,这只是激活函数。可以参考源代码编写
    # 2. 重写build方法,因为没有初始化参数,所以不需要重写
    """

    # 3. 重写call()方法,其实现运算功能
    def call(self, inputs):
        # 这部分不建议绑定self,因为可能会重名
        inputs -= K.mean(inputs, axis=1, keepdims=True)
        inputs = K.l2_normalize(inputs, axis=1)
        pos = K.relu(inputs)
        neg = K.relu((-inputs))
        return K.concatenate([pos, neg], axis=1)

    # 4.重写compute_output_shape
    def compute_output_shape(self, input_shape):
        shape = list(input_shape)
        assert len(shape) == 2
        shape[-1] *= 2
        return tuple(shape)

# -----------------------------------------------------------
batch_size = 128
num_classes = 10
epochs = 40

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

# build the model
model = Sequential()
model.add(Dense(256, input_shape=(784,)))
model.add(Antirectifier())
model.add(Dropout(0.1))
model.add(Dense(256))
model.add(Antirectifier())
model.add(Dropout(0.1))
model.add(Dense(num_classes))
model.add(Activation('softmax'))

# compile the model
model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# train the model
model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
# next, compare with an equivalent network with2x bigger Dense layers and ReLU
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Keras LSTM是一种深度学习模型常用的循环神经网络结构,它能够在处理序列数据时具有优秀的性能。三Keras LSTM模型意味着在网络使用了三个LSTM。 LSTM(Long Short-Term Memory)是一种特殊的循环神经网络结构,它通过内部的门控机制能够有效地捕捉并记忆长期依赖关系。LSTM的数量越多,模型就具备了更强的记忆能力和更复杂的表示能力。 在使用Keras构建LSTM三模型时,可以通过Sequential或Functional API两种方式。Sequential用于构建序列模型,而Functional API更适用于构建更复杂的模型结构。 具体实现LSTM三模型时,可以通过以下代码示例: ```python from keras.models import Sequential from keras.layers import LSTM model = Sequential() model.add(LSTM(units=64, return_sequences=True, input_shape=(timesteps, input_dim))) model.add(LSTM(units=64, return_sequences=True)) model.add(LSTM(units=64)) model.add(Dense(units=num_classes, activation='softmax')) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) ``` 上述代码,模型使用了三个LSTM,每个LSTM的units参数定义了该的输出维度。return_sequences=True表示每个LSTM都会返回一个包含完整输出序列的3D张量,而最后一个LSTM上可以不设置return_sequences参数,默认为False。模型的最后一是一个全连接,用于分类任务。 在模型编译之后,可以使用fit函数来训练该模型,并根据需要对其进行评估和预测。 总而言之,Keras LSTM三模型在处理序列数据上具有较强的表达能力和记忆能力,可以用来解决各种序列相关的问题,如自然语言处理、时间序列预测等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值