如何在Tensorflow中实现自定义RNN(特别是ESN)?

时间:2015-11-23 19:41:37

标签: python machine-learning neural-network tensorflow

根据以下定义,我试图在Tensorflow中定义自己的RNNCell(回声状态网络)。

x(t + 1)= tanh(Win * u(t)+ W * x(t)+ Wfb * y(t))

y(t)= Wout * z(t)

z(t)= [x(t),u(t)]

x是状态,u是输入,y是输出。 Win,W和Wfb不可训练。所有权重都是随机初始化的,但W的修改方式如下:"将W的元素的某个百分比设置为0,将W的比例设置为低于1.0

我有这个代码来生成方程式。

x = tf.Variable(tf.reshape(tf.zeros([N]), [-1, N]), trainable=False, name="state_vector")
W = tf.Variable(tf.random_normal([N, N], 0.0, 0.05), trainable=False)
# TODO: setup W according to the ESN paper
W_x = tf.matmul(x, W)

u = tf.placeholder("float", [None, K], name="input_vector")
W_in = tf.Variable(tf.random_normal([K, N], 0.0, 0.05), trainable=False)
W_in_u = tf.matmul(u, W_in)

z = tf.concat(1, [x, u])
W_out = tf.Variable(tf.random_normal([K + N, L], 0.0, 0.05))
y = tf.matmul(z, W_out)
W_fb = tf.Variable(tf.random_normal([L, N], 0.0, 0.05), trainable=False)
W_fb_y = tf.matmul(y, W_fb)

x_next = tf.tanh(W_in_u + W_x + W_fb_y)

y_ = tf.placeholder("float", [None, L], name="train_output")

我的问题是双重的。首先,我不知道如何将其作为RNNCell的超类来实现。其次,我不知道如何根据上述规范生成W张量。

非常感谢任何有关这些问题的帮助。也许我可以找到一种方法来准备W,但我确定不知道如何将我自己的RNN实现为RNNCell的超类。

2 个答案:

答案 0 :(得分:11)

快速总结一下:

查看python/ops/rnn_cell.py下的TensorFlow源代码,了解如何子类 RNNCell。它通常是这样的:

class MyRNNCell(RNNCell):
  def __init__(...):

  @property
  def output_size(self):
  ...

  @property
  def state_size(self):
  ...

  def __call__(self, input_, state, name=None):
     ... your per-step iteration here ...

答案 1 :(得分:0)

我可能会迟到一些,但对于任何尝试这样做的人,tensorflow-addons添加了ESNCellESN layer的实现。