Paddle
Paddle copied to clipboard
fluid.layers.DynamicRNN()用法咨询
import numpy as np
import time
import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle.fluid.framework as framework
from paddle.fluid.executor import Executor
def to_lodtensor(data, place):
seq_lens = [len(seq) for seq in data]
cur_len = 0
lod = [cur_len]
for l in seq_lens:
cur_len += l
lod.append(cur_len)
flattened_data = np.concatenate(data, axis=0).astype("float32")
res = fluid.LoDTensor()
res.set(flattened_data, place)
res.set_lod([lod])
return res
shape = [1]
gate_size = 2
data = fluid.layers.data(name='data', shape=shape, dtype='float32')
input_forward_proj = fluid.layers.fc(name='fc_0',input=data,
size=gate_size * 4,
act=None,
bias_attr=False)
forward, state = fluid.layers.dynamic_lstm(
name='blstm_0',
input=input_forward_proj, size=gate_size * 4,use_peepholes=False)
place = fluid.CPUPlace()
feeder = fluid.DataFeeder(place=place,feed_list=[data])
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
tensor_x = [np.array([[1],[2]])]
lod_tensor = to_lodtensor(tensor_x, place)
results = exe.run(fluid.default_main_program(),
feed={'data':lod_tensor},
fetch_list=[forward],return_numpy=False)
print np.array( results[0] )
我想用 rnn = fluid.layers.DynamicRNN()自定义来实现一下这个功能。要怎么办呢?
PS:lstm_step已经实现了,我参照attention例子抄了一遍,不太理解step_input和static_input的含义。无法运行成功
def lstm_step(x_t, hidden_t_prev, cell_t_prev, size):
def linear(inputs):
return fluid.layers.fc(input=inputs, size=size, bias_attr=True)
forget_gate = fluid.layers.sigmoid(x=linear([hidden_t_prev, x_t]))
input_gate = fluid.layers.sigmoid(x=linear([hidden_t_prev, x_t]))
output_gate = fluid.layers.sigmoid(x=linear([hidden_t_prev, x_t]))
cell_tilde = fluid.layers.tanh(x=linear([hidden_t_prev, x_t]))
cell_t = fluid.layers.sums(input=[
fluid.layers.elementwise_mul(
x=forget_gate, y=cell_t_prev), fluid.layers.elementwise_mul(
x=input_gate, y=cell_tilde)
])
hidden_t = fluid.layers.elementwise_mul(
x=output_gate, y=fluid.layers.tanh(x=cell_t))
return hidden_t, cell_t
shape = [1]
gate_size = 2
data = fluid.layers.data(name='data', shape=shape, dtype='float32')
rnn = fluid.layers.DynamicRNN()
cell_init = fluid.layers.fill_constant_batch_size_like(
input=data,
value=0.0,
shape=[-1, gate_size],
dtype='float32')
cell_init.stop_gradient = False
hidden_init = fluid.layers.fill_constant_batch_size_like(
input=data,
value=0.0,
shape=[-1, gate_size],
dtype='float32')
hidden_init.stop_gradient = False
with rnn.block():
encoder_vec = rnn.static_input(data)
cell_mem = rnn.memory(init=cell_init)
hidden_mem = rnn.memory(init=hidden_init, need_reorder=True)
h, c = lstm_step(encoder_vec, hidden_mem, cell_mem, gate_size)
rnn.update_memory(hidden_mem, h)
rnn.update_memory(cell_mem, c)
out = fluid.layers.fc(input=h,
size=target_dict_dim,
bias_attr=True,
act='softmax')
rnn.output(out)
lstm1 = rnn()
报错
RuntimeErrorTraceback (most recent call last)
<ipython-input-3-f7e0139c50cb> in <module>()
22
23 with rnn.block():
---> 24 encoder_vec = rnn.static_input(data)
25 cell_mem = rnn.memory(init=cell_init)
26 hidden_mem = rnn.memory(init=hidden_init, need_reorder=True)
1386 if self.lod_rank_table is None:
1387 raise RuntimeError(
-> 1388 "static_input() must be called after step_input().")
1389 parent_block = self._parent_block_()
1390 x_reordered = parent_block.create_var(
RuntimeError: static_input() must be called after step_input().
实现了,这是我的实现方式:
import numpy as np
import time
import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle.fluid.framework as framework
from paddle.fluid.executor import Executor
def lstm_step(x_t, hidden_t_prev, cell_t_prev, size):
def linear(inputs,name):
return fluid.layers.fc(input=inputs,name=name, size=size, bias_attr=True)
forget_gate = fluid.layers.sigmoid(x=linear([hidden_t_prev, x_t],'forget'))
input_gate = fluid.layers.sigmoid(x=linear([hidden_t_prev, x_t],'input'))
output_gate = fluid.layers.sigmoid(x=linear([hidden_t_prev, x_t],'output'))
cell_tilde = fluid.layers.tanh(x=linear([hidden_t_prev, x_t],'c'))
cell_t = fluid.layers.sums(input=[
fluid.layers.elementwise_mul(
x=forget_gate, y=cell_t_prev), fluid.layers.elementwise_mul(
x=input_gate, y=cell_tilde)
])
hidden_t = fluid.layers.elementwise_mul(
x=output_gate, y=fluid.layers.tanh(x=cell_t))
return hidden_t, cell_t
shape = [1]
gate_size = 2
data = fluid.layers.data(name='data', shape=shape, dtype='float32')
rnn = fluid.layers.DynamicRNN()
cell_init = fluid.layers.fill_constant_batch_size_like(
input=data,
value=0.0,
shape=[-1, gate_size],
dtype='float32')
cell_init.stop_gradient = False
hidden_init = fluid.layers.fill_constant_batch_size_like(
input=data,
value=0.0,
shape=[-1, gate_size],
dtype='float32')
hidden_init.stop_gradient = False
with rnn.block():
encoder_vec = rnn.step_input(data)
cell_mem = rnn.memory(init=cell_init)
hidden_mem = rnn.memory(init=hidden_init, need_reorder=True)
h, c = lstm_step(encoder_vec, hidden_mem, cell_mem, gate_size)
rnn.update_memory(hidden_mem, h)
rnn.update_memory(cell_mem, c)
rnn.output(c)
lstm1 = rnn()
place = fluid.CPUPlace()
feeder = fluid.DataFeeder(place=place,feed_list=[data])
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
tensor_x = [np.array([[1],[2]])]
lod_tensor = to_lodtensor(tensor_x, place)
results = exe.run(fluid.default_main_program(),
feed={'data':lod_tensor},
fetch_list=[lstm1],return_numpy=False)
print np.array( results[0] )
不过依然不太明白,static_input和step_input在DynamicRNN()中分别起了什么作用??
这个与Paddle处理序列数据的方式有关,在处理序列数据时会根据batch中序列长度降序排序,每个时间步会取各序列中对应时间步的数据,清晰的图示可以参考这里 https://github.com/PaddlePaddle/Paddle/wiki/Paddle目前的实现的各个模块细节#rnn单元 ;step_input即是取排序后当前时间步的数据(用于如target word),static_input用于对所有时间步都不变的数据(如attention模型中来自encoder的context,这些数据也会随step_input中指定的数据一起排序,而且严格来说不同时间步也是有可能改变的--某个序列处理完成后数据的收缩),暴露出来的api隐藏了一些细节,如上面所说的排序、某个序列处理完成后数据的收缩。