keras - 将 Tensorflow1 转换为 Tensorflow 2
问题描述
此链接上有一个用 tensorflow1 编写的代码。 https://github.com/carlthome/tensorflow-convlstm-cell/blob/master/cell.py 我想在TensorFlow.Keras中使用这个类作为一个层。所以应该是用TensorFlow版本2写的,怎么做呢?这是这段代码: import tensorflow as tf
class ConvLSTMCell(tf.nn.rnn_cell.RNNCell):
"""A LSTM cell with convolutions instead of multiplications.
Reference:
Xingjian, S. H. I., et al. "Convolutional LSTM network: A machine learning approach for precipitation nowcasting." Advances in Neural Information Processing Systems. 2015.
"""
def __init__(self, shape, filters, kernel, forget_bias=1.0, activation=tf.tanh, normalize=True, peephole=True, data_format='channels_last', reuse=None):
super(ConvLSTMCell, self).__init__(_reuse=reuse)
self._kernel = kernel
self._filters = filters
self._forget_bias = forget_bias
self._activation = activation
self._normalize = normalize
self._peephole = peephole
if data_format == 'channels_last':
self._size = tf.TensorShape(shape + [self._filters])
self._feature_axis = self._size.ndims
self._data_format = None
elif data_format == 'channels_first':
self._size = tf.TensorShape([self._filters] + shape)
self._feature_axis = 0
self._data_format = 'NC'
else:
raise ValueError('Unknown data_format')
@property
def state_size(self):
return tf.nn.rnn_cell.LSTMStateTuple(self._size, self._size)
@property
def output_size(self):
return self._size
def call(self, x, state):
c, h = state
x = tf.concat([x, h], axis=self._feature_axis)
n = x.shape[-1].value
m = 4 * self._filters if self._filters > 1 else 4
W = tf.get_variable('kernel', self._kernel + [n, m])
y = tf.nn.convolution(x, W, 'SAME', data_format=self._data_format)
if not self._normalize:
y += tf.get_variable('bias', [m], initializer=tf.zeros_initializer())
j, i, f, o = tf.split(y, 4, axis=self._feature_axis)
if self._peephole:
i += tf.get_variable('W_ci', c.shape[1:]) * c
f += tf.get_variable('W_cf', c.shape[1:]) * c
if self._normalize:
j = tf.contrib.layers.layer_norm(j)
i = tf.contrib.layers.layer_norm(i)
f = tf.contrib.layers.layer_norm(f)
f = tf.sigmoid(f + self._forget_bias)
i = tf.sigmoid(i)
c = c * f + i * self._activation(j)
if self._peephole:
o += tf.get_variable('W_co', c.shape[1:]) * c
if self._normalize:
o = tf.contrib.layers.layer_norm(o)
c = tf.contrib.layers.layer_norm(c)
o = tf.sigmoid(o)
h = o * self._activation(c)
state = tf.nn.rnn_cell.LSTMStateTuple(c, h)
return h, state
解决方案
推荐阅读
- java - Apache Kafka Streams - 无法与窗口聚合
- oracle - 为什么它在没有 PRAGMA AUTONOMOUS_TRANSACTION 的情况下工作
- c - 我应该使用位域来映射传入的串行数据吗?
- r - 给时间索引号
- laravel - 如何集成单独工作的 Laravel 和 Vue 代码不能很好地协同工作
- json.net - JSON.Net Schema 多个自定义验证
- laravel - 如何防止并发发布请求?
- javascript - 刷新(重新调用)API 的反应按钮
- google-cloud-platform - 打开我的 Google Cloud Run 服务的 URL 时出现 401 未经授权的错误
- symfony - ManyToMany 新值必须是数组或 \Traversable 的实例,给定“NULL”