根据py_func文档的解释,在使用这个接口时是需要指定输出的shape和data type的,但不意味着这个函数在构建模型时就已经被执行。如果你只是希望将可变长shape从[-1, 2]变成[-1, 1],你可以这么试试,
import paddle.fluid as fluidimport numpy as npdef create_tmp_var(name, dtype, shape): return fluid.default_main_program().current_block().create_var( name=name, dtype=dtype, shape=shape)def my_size(x): num_cls_prob = np.size(np.array(x)) cls_prob_reshpae = np.reshape(np.array(x), [num_cls_prob, -1]) return cls_prob_reshpaecls_prob = create_tmp_var(name='num_cls', dtype='int64', shape=[-1, 2])cls_prob_reshpae = create_tmp_var(name='num_cls_prob', dtype='int64', shape=[-1, 1])cls_prob_reshpae = fluid.layers.py_func(func=my_size, x=cls_prob, out=cls_prob_reshpae)print(cls_prob_reshpae)
这样print的cls_prob_reshpae如下:
name: "num_cls_prob"type { type: LOD_TENSOR lod_tensor { tensor { data_type: INT64 dims: -1 dims: 1 } }}