Implementing a tensorflow graph into a Keras model

冷暖自知 提交于 2019-12-06 04:06:52

I'm not sure if I fully understand your needs. Based on your tensorflow code, I don't think you will have to feed in the initial value. In that case, I hope the following is at least close to what you want:

import numpy as np
import keras
from keras import backend as K
from keras.engine.topology import Layer
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Add

class MyLayer(Layer):

    def __init__(self, bias_init, **kwargs):
        self.bias_init = bias_init
        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        self.bias = self.add_weight(name='bias',
                                    shape=input_shape[1:],
                                    initializer=keras.initializers.Constant(self.bias_init),
                                    trainable=True)
        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

    def call(self, x):
        return x + self.bias

input0    = Input((28,28,1))
x         = Conv2D(32, kernel_size=(3, 3), activation='relu',input_shape=(28,28,1))(input0)
x         = Conv2D(64, (3, 3), activation='relu')(input0)
x         = MaxPooling2D(pool_size=(2, 2))(x)
x         = Flatten()(x)
x         = Dense(128, activation='relu')(x)

input1    = np.random.rand(128)

x         = MyLayer(input1)(x)
x         = Dense(10, activation='softmax')(x)
model     = Model(inputs=input0, outputs=x)
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!