将张量流图实现为Keras模型

时间:2018-05-01 16:32:26

标签: python tensorflow keras keras-layer

我正在尝试在Keras(最好)或Tensorflow中大致实现以下架构。

          ___________      _________      _________     ________    ______
          | Conv    |     | Max    |     | Dense  |    |       |   |     |
Input0--> | Layer 1 | --> | Pool 1 | --> | Layer  | -->|       |   |     |
          |_________|     |________|     |________|    | Sum   |   | Out |
                                                       | Layer |-->|_____|
Input1    ----------- Converted to trainable weights-->|       |              
                                                       |_______|                                                                               |_______|

简而言之,它几乎是一个带有两个输入的模型,使用Add([input0,input1])层合并到一个输出中。诀窍是其中一个输入必须被视为变量=可训练的重量。

Keras层Add()不允许这样做,它将input0和input1作为不可训练的变量:

input0    = Input((28,28,1))
x         = Conv2D(32, kernel_size=(3, 3), activation='relu',input_shape=input_shape)(mod1)
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    = Input((128,))

x         = Add()([x, input1])
x         = Dense(num_classes, activation='softmax')(x)
model     = Model(inputs = [mod1,TPM], outputs = x)
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

我可以在tensorflow中实现一个图表,它添加一个带有权重b的占位符X,并学习b相对于目标Y的值。

train_X = numpy.asarray([1.0, 2.0])
train_Y = numpy.asarray([0.0, 2.5])
n_samples = train_X.shape[0]

# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")

# Set model weights
b = tf.Variable([0.0, 0.0], name="bias")

# Construct a linear model
pred = tf.add(X, b)

loss = tf.reduce_mean(tf.square(pred - train_Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
grads_and_vars = optimizer.compute_gradients(loss)

train = optimizer.apply_gradients(grads_and_vars)
#init = tf.initialize_all_variables()
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for step in range(epochs):
    sess.run(train, feed_dict={X: train_X, Y: train_Y})

我的工作很有意义。简单优化的输入和权重添加。但是我不能把它包含在Keras模型中。我错过了如何合并这两个想法的步骤。

如何包含一个只将一个可训练张量与一个不可训练的张量相加的图层?

1 个答案:

答案 0 :(得分:1)

我不确定我是否完全了解您的需求。根据您的张量流代码,我认为您不必提供初始值。在这种情况下,我希望以下内容至少接近你想要的内容:

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