以类似"细胞"的方式使用标准张量流层



我的问题与这个问题有关*。

是否有可能将标准的张量流层转换为"细胞",与RNN细胞一起使用以组成递归神经网络?

因此,新的"单元格"应该存储参数(权重等),并且能够在不同的输入上调用。像这样:

from tf.nn import batch_normalization, conv2d
from tf.contrib.rnn import MultiRNNCell, LSTMCell
bn_cell = cell_creation_fun(batch_normalization, otherparams) # batch norm cell
conv_cell = cell_creation_fun(conv2d, otherparams )           # non-rnn conv cell
# or `conv_cell = cell_creation_fun(tf.layers.Conv2D, otherparams )` # using tf.layers  

这样它们就可以像这样使用:

multi_cell = MultiRNNCell([LSTMCell(...), conv_cell, bn_cell])

或者像这样:

h = ...
conv_h, _ = conv_cell(h, state=None)
normed_h, _ = bn_cell(h, state=None)

我唯一能想到的就是为我想使用的每一层手动编写这样一个"单元格",对 RNNCell 进行子类化。但是,使用Conv2D等现有函数而不能够在创建过程中传递"输入"参数似乎并不简单。(当我管理时会发布代码。


*也许以更有针对性的方式询问有机会得到答案。

好的,这是我到目前为止所拥有的:

class LayerCell(rnn_cell_impl.RNNCell):
def __init__(self, tf_layer, **kwargs):
''' :param tf_layer: a tensorflow layer, e.g. tf.layers.Conv2D or 
tf.keras.layers.Conv2D. NOT tf.layers.conv2d !'''
self.layer_fn = tf_layer(**kwargs)
def __call__(self, inputs, state, scope=None):
''' Every `RNNCell` must implement `call` with
the signature `(output, next_state) = call(input, state)`.  The optional
third input argument, `scope`, is allowed for backwards compatibility
purposes; but should be left off for new subclasses.'''
return (self.layer_fn(inputs), state)
def __str__(self):
return "Cell wrapper of " + str(self.layer_fn)
def __getattr__(self, attr):
'''credits to https://stackoverflow.com/questions/1382871/dynamically-attaching-a-method-to-an-existing-python-object-generated-with-swig/1383646#1383646'''
return getattr(self.layer_fn, attr)
@property
def state_size(self):
"""size(s) of state(s) used by this cell.
It can be represented by an Integer, a TensorShape or a tuple of Integers
or TensorShapes.
"""
return  (0,) 
@property
def output_size(self):
"""Integer or TensorShape: size of outputs produced by this cell."""
# use with caution; could be uninitialized
return self.layer_fn.output_shape

(当然,不要与循环层一起使用,因为状态保持将被破坏。

似乎适用于: tf.layers.Conv2D, tf.keras.layers.Conv2D,tf.keras.layers.Activation, tf.layers.BatchNormalization

不适用于:tf.keras.layers.BatchNormalization。至少在 tf.while 循环中使用它时对我来说失败了; 抱怨组合来自不同帧的变量,类似于这里。也许 keras 使用 tf。变量()而不是tf.get_variable()...?


使用权:

cell0 = tf.contrib.rnn.ConvLSTMCell(conv_ndims=2, input_shape=[40, 40, 3], output_channels=16, kernel_shape=[5, 5])
cell1 = LayerCell(tf.keras.layers.Conv2D, filters=8, kernel_size=[5, 5], strides=(1, 1), padding='same')
cell2 = LayerCell(tf.layers.BatchNormalization, axis=-1)
inputs =  np.random.rand(10, 40, 40, 3).astype(np.float32)
multicell = tf.contrib.rnn.MultiRNNCell([cell0, cell1, cell2])
state = multicell.zero_state(batch_size=10, dtype=tf.float32)
output = multicell(inputs, state)
print("Yippee!")

最新更新