Paddle
Paddle copied to clipboard
sequence_expand 使用咨询
我想复现你们api中的demo。 sequence-expand
貌似并没有像我预期的运行?
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):
""" convert to LODtensor """
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("int64")
res = fluid.LoDTensor()
res.set(flattened_data, place)
res.set_lod([lod])
return res
x = fluid.layers.data(name='x', shape=[1], dtype='float32')
y = fluid.layers.data(name='y', shape=[5],
dtype='float32')
out = fluid.layers.sequence_expand(x=x, y=y, ref_level=-1)
place = fluid.CPUPlace()
feeder = fluid.DataFeeder(place=place,feed_list=[x,y])
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
x_d = to_lodtensor( [ np.array( [ [0],[1],[2],[3] ])] , place)
y_d = to_lodtensor( [ np.array( [0, 3, 6, 7, 8] ) ], place)
results = exe.run(fluid.default_main_program(),
feed={'x':x_d, 'y': y_d },
fetch_list=[out],return_numpy=False)
print np.array(results[0]).shape
print np.array(results[0])
输出了
(20, 1)
[[0]
[1]
[2]
[3]
[0]
[1]
[2]
[3]
[0]
[1]
[2]
[3]
[0]
[1]
[2]
[3]
[0]
[1]
[2]
[3]]
而不是demo里写的[ [0],[1],[0],[1],[2],[3],[2], [3] ] ??
需要正确的设置LoD和数据
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 create_lod_tensor(data, lod, place):
# flattened_data = np.concatenate(data, axis=0).astype("float32")
res = fluid.LoDTensor()
res.set(data, place)
res.set_lod(lod)
return res
x = fluid.layers.data(name='x', shape=[1], dtype='float32', lod_level=0)
y = fluid.layers.data(name='y', shape=[5], dtype='float32', lod_level=1)
out = fluid.layers.sequence_expand(x=x, y=y, ref_level=0)
place = fluid.CPUPlace()
feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
# x_d = to_lodtensor([np.array([[0], [1], [2], [3]])], place)
# y_d = to_lodtensor([np.array([[0, 3, 6, 7, 8]])], place)
x_d = create_lod_tensor(np.array([[0], [1], [2], [3]]), [[0, 2, 4]], place)
y_d = create_lod_tensor(np.array([[0]]), [[0, 2, 4], [0, 3, 6, 7, 8]], place)
results = exe.run(fluid.default_main_program(),
feed={'x':x_d, 'y': y_d },
fetch_list=[out],return_numpy=False)
print(results[0].lod())
print(np.array(results[0]))
print(results[0].shape())
结果:
[[0L, 2L, 4L, 6L, 8L]]
[[0]
[1]
[0]
[1]
[2]
[3]
[2]
[3]]
[8L, 1L]