\u200E
  • 开始使用
  • 特性
  • 文档
    • API
    • 使用指南
  • 工具平台
    • 工具
      • AutoDL
  • develop
  • 2.0-rc1
  • 1.8
  • 1.7
  • 1.6
  • 1.5
  • 1.4
  • 1.3
  • 1.2
  • 1.1
  • 1.0
  • 0.15.0
  • 0.14.0
  • 0.13.0
  • 0.12.0
  • 0.11.0
  • 0.10.0
  • 中文(简)
  • English(En)
  • 安装说明
    • Pip安装
      • Linux下的PIP安装
      • Windows下的PIP安装
      • MacOS下的PIP安装
    • Conda安装
      • Linux下的Conda安装
      • Windows下的Conda安装
      • MacOS下的Conda安装
    • 从源码编译
      • Linux下从源码编译
      • Windows下从源码编译
      • MacOS下从源码编译
    • docker安装
      • 使用Docker安装
    • 附录
  • 快速上手
    • 基本概念
      • 编程指南
      • Variable
      • Tensor
      • LoDTensor
      • Operator
      • Program
      • Executor
      • 命令式编程使用教程
    • 编程实践
      • Reader
      • 配置简单的网络
      • 单机训练
        • 训练过程中评测模型
      • 模型/变量的保存、载入与增量训练
  • 典型案例
    • 简单案例
      • 线性回归
      • 数字识别
      • 词向量
    • 计算机视觉
      • 图像分类
      • 生成对抗网络
    • 自然语言处理
      • 情感分析
      • 语义角色标注
      • 机器翻译
    • 推荐
      • 个性化推荐
    • 工具组件
      • ELASTIC CTR
      • 飞桨大规模分类库简介
  • 进阶指南
    • 准备数据
      • 声明式编程模式(静态图)
        • 准备步骤
        • 数据预处理工具
        • 异步数据读取
        • 同步数据读取
      • 命令式编程模式(动态图)
        • 数据准备、载入及加速
    • 分布式训练
      • 分布式训练快速开始
      • 使用FleetAPI进行分布式训练
    • 预测部署
      • 服务器端部署
        • 安装与编译 Linux 预测库
        • 安装与编译 Windows 预测库
        • C++ 预测 API介绍
        • C 预测 API介绍
        • Python 预测 API介绍
      • 移动端部署
        • Paddle-Lite
      • 模型压缩
    • 性能调优
      • 单机训练优秀实践
      • 存储分配与优化
      • 运行时设备切换
      • 混合精度训练最佳实践
      • 分布式CPU训练优秀实践
      • 分布式GPU训练优秀实践
      • 重计算:大Batch训练特性
      • 使用Paddle-TensorRT库预测
      • 性能优化分析及工具
        • CPU性能调优
        • timeline工具简介
    • 模型评估/调试
      • 模型评估
      • VisualDL 工具
        • VisualDL 工具简介
        • VisualDL 使用指南
    • 二次开发
      • 设计思想
      • 新增OP
        • 如何写新的C++ OP
        • C++ OP相关注意事项
        • 如何写新的Python OP
        • 如何在框架外部自定义C++ OP
      • 如何贡献代码
        • 本地开发指南
        • 提交PR注意事项
        • FAQ
    • 环境变量FLAGS
      • cudnn
      • 数值计算
      • 调试
        • check nan inf工具
      • 设备管理
      • 分布式
      • 执行器
      • 存储管理
      • 其他
  • API Reference
    • API功能分类
      • 基础概念
      • 神经网络层
        • 卷积
        • 池化
        • 图像检测
        • 序列
        • 数学操作
        • 激活函数
        • 损失函数
        • 数据输入输出
        • 控制流
        • 稀疏更新
        • 使用DataFeeder传入训练/预测数据
        • 学习率调度器
        • 张量
      • 复杂网络
      • 优化器
      • 反向传播
      • 评价指标
      • 模型保存与加载
      • 预测引擎
      • 执行引擎
      • 数据并行执行引擎
      • CompiledProgram
      • 模型参数
      • 分布式训练
        • 分布式同步训练
        • 分布式异步训练
        • 大规模稀疏特征模型训练
        • 分布式训练reader准备
      • TensorFlow-Fluid常用接口对应表
      • Caffe-Fluid常用层对应表
    • fluid
      • BuildStrategy
      • CompiledProgram
      • ComplexVariable
      • cpu_places
      • CPUPlace
      • create_lod_tensor
      • create_random_int_lodtensor
      • cuda_pinned_places
      • cuda_places
      • CUDAPinnedPlace
      • CUDAPlace
      • data
      • DataFeedDesc
      • DataFeeder
      • default_main_program
      • default_startup_program
      • disable_dygraph
      • disable_imperative
      • device_guard
      • DistributeTranspiler
      • DistributeTranspilerConfig
      • embedding
      • enable_dygraph
      • enable_imperative
      • ExecutionStrategy
      • Executor
      • get_flags
      • global_scope
      • gradients
      • in_dygraph_mode
      • is_compiled_with_cuda
      • load
      • load_op_library
      • LoDTensor
      • LoDTensorArray
      • memory_optimize
      • name_scope
      • one_hot
      • ParallelExecutor
      • ParamAttr
      • Program
      • program_guard
      • release_memory
      • require_version
      • save
      • scope_guard
      • set_flags
      • Tensor
      • Variable
      • WeightNormParamAttr
    • fluid.backward
      • append_backward
      • gradients
    • fluid.clip
      • ErrorClipByValue
      • GradientClipByGlobalNorm
      • GradientClipByNorm
      • GradientClipByValue
      • set_gradient_clip
    • dataset
      • cifar
      • Conll05
      • imdb
      • imikolov
      • mnist
      • movielens
      • sentiment
      • uci_housing
      • wmt14
      • wmt16
    • fluid.dataset
      • DatasetFactory
      • InMemoryDataset
      • QueueDataset
    • fluid.dygraph
      • BackwardStrategy
      • BatchNorm
      • BCELoss
      • BilinearTensorProduct
      • Conv2D
      • Conv2DTranspose
      • Conv3D
      • Conv3DTranspose
      • CosineDecay
      • DataParallel
      • disable_dygraph
      • disable_imperative
      • Dropout
      • declarative
      • Embedding
      • enable_dygraph
      • enable_imperative
      • enabled
      • ExponentialDecay
      • grad
      • GroupNorm
      • GRUUnit
      • guard
      • InstanceNorm
      • InverseTimeDecay
      • L1Loss
      • Layer
      • LayerList
      • LayerNorm
      • Linear
      • load_dygraph
      • MSELoss
      • NaturalExpDecay
      • NCE
      • NLLLoss
      • NoamDecay
      • ParallelEnv
      • ParameterList
      • no_grad
      • PiecewiseDecay
      • PolynomialDecay
      • Pool2D
      • PRelu
      • prepare_context
      • ProgramTranslator
      • save_dygraph
      • Sequential
      • SpectralNorm
      • to_variable
      • TracedLayer
      • TreeConv
    • fluid.executor
      • Executor
      • global_scope
      • scope_guard
    • fluid.initializer
      • Bilinear
      • BilinearInitializer
      • Constant
      • ConstantInitializer
      • MSRA
      • MSRAInitializer
      • Normal
      • NormalInitializer
      • NumpyArrayInitializer
      • TruncatedNormal
      • TruncatedNormalInitializer
      • Uniform
      • UniformInitializer
      • Xavier
      • XavierInitializer
    • fluid.io
      • batch
      • buffered
      • cache
      • chain
      • compose
      • ComposeNotAligned
      • DataLoader
      • firstn
      • get_program_parameter
      • get_program_persistable_vars
      • load
      • load_inference_model
      • load_params
      • load_persistables
      • load_program_state
      • load_vars
      • map_readers
      • multiprocess_reader
      • PyReader
      • save
      • save_inference_model
      • save_params
      • save_persistables
      • save_vars
      • set_program_state
      • shuffle
      • xmap_readers
    • fluid.layers
      • abs
      • accuracy
      • acos
      • adaptive_pool2d
      • adaptive_pool3d
      • add_position_encoding
      • addcmul
      • addmm
      • affine_channel
      • affine_grid
      • allclose
      • anchor_generator
      • arange
      • argmax
      • argmin
      • argsort
      • array_length
      • array_read
      • array_write
      • asin
      • assign
      • atan
      • auc
      • autoincreased_step_counter
      • batch_norm
      • BasicDecoder
      • beam_search
      • beam_search_decode
      • bilinear_tensor_product
      • bipartite_match
      • bmm
      • box_clip
      • box_coder
      • box_decoder_and_assign
      • bpr_loss
      • brelu
      • BeamSearchDecoder
      • case
      • cast
      • Categorical
      • ceil
      • center_loss
      • chunk_eval
      • clamp
      • clip_by_norm
      • clip
      • collect_fpn_proposals
      • concat
      • cond
      • continuous_value_model
      • conv2d
      • conv2d_transpose
      • conv3d
      • conv3d_transpose
      • cos
      • cos_sim
      • cosine_decay
      • create_array
      • create_global_var
      • create_parameter
      • create_py_reader_by_data
      • create_tensor
      • crf_decoding
      • crop
      • crop_tensor
      • cross
      • cross_entropy
      • ctc_greedy_decoder
      • cumsum
      • data
      • data_norm
      • deformable_conv
      • deformable_roi_pooling
      • density_prior_box
      • detection_output
      • diag
      • diag_embed
      • dice_loss
      • dist
      • distribute_fpn_proposals
      • dot
      • double_buffer
      • dropout
      • dynamic_gru
      • dynamic_lstm
      • dynamic_lstmp
      • dynamic_decode
      • Decoder
      • DecodeHelper
      • DynamicRNN
      • edit_distance
      • elementwise_add
      • elementwise_div
      • elementwise_equal
      • elementwise_floordiv
      • elementwise_max
      • elementwise_min
      • elementwise_mod
      • elementwise_mul
      • elementwise_pow
      • elementwise_sub
      • elu
      • embedding
      • equal
      • erf
      • exp
      • expand
      • expand_as
      • exponential_decay
      • eye
      • fc
      • fill_constant
      • filter_by_instag
      • flatten
      • flip
      • floor
      • fsp_matrix
      • full
      • full_like
      • gather
      • gather_nd
      • gather_tree
      • gaussian_random
      • gelu
      • generate_mask_labels
      • generate_proposal_labels
      • generate_proposals
      • get_tensor_from_selected_rows
      • greater_equal
      • greater_than
      • GreedyEmbeddingHelper
      • grid_sampler
      • group_norm
      • gru_unit
      • GRUCell
      • hard_shrink
      • hard_sigmoid
      • hard_swish
      • has_inf
      • has_nan
      • hash
      • hsigmoid
      • huber_loss
      • IfElse
      • im2sequence
      • image_resize
      • image_resize_short
      • increment
      • inverse_time_decay
      • index_select
      • inplace_abn
      • instance_norm
      • interpolate
      • iou_similarity
      • is_empty
      • isfinite
      • kldiv_loss
      • kron
      • l2_normalize
      • label_smooth
      • layer_norm
      • leaky_relu
      • less_equal
      • less_than
      • linear_chain_crf
      • linear_lr_warmup
      • linspace
      • load
      • locality_aware_nms
      • lod_append
      • lod_reset
      • log
      • log1p
      • log_loss
      • log_softmax
      • logical_and
      • logical_not
      • logical_or
      • logical_xor
      • logsigmoid
      • logsumexp
      • lrn
      • lstm
      • lstm_unit
      • LSTMCell
      • margin_rank_loss
      • matmul
      • maxout
      • mean
      • mean_iou
      • merge_selected_rows
      • meshgrid
      • mse_loss
      • mul
      • multi_box_head
      • multiclass_nms
      • multiplex
      • MultivariateNormalDiag
      • natural_exp_decay
      • nce
      • noam_decay
      • nonzero
      • Normal
      • not_equal
      • npair_loss
      • one_hot
      • ones
      • ones_like
      • pad
      • pad_constant_like
      • pad2d
      • piecewise_decay
      • pixel_shuffle
      • polygon_box_transform
      • polynomial_decay
      • pool2d
      • pool3d
      • pow
      • prelu
      • Print
      • prior_box
      • prroi_pool
      • psroi_pool
      • py_func
      • py_reader
      • randint
      • randn
      • random_crop
      • range
      • randperm
      • rank
      • rank_loss
      • read_file
      • reciprocal
      • reduce_all
      • reduce_any
      • reduce_max
      • reduce_mean
      • reduce_min
      • reduce_prod
      • reduce_sum
      • relu
      • relu6
      • reorder_lod_tensor_by_rank
      • reshape
      • resize_bilinear
      • resize_nearest
      • resize_trilinear
      • retinanet_detection_output
      • retinanet_target_assign
      • reverse
      • rnn
      • roi_align
      • roi_perspective_transform
      • roi_pool
      • roll
      • round
      • row_conv
      • rpn_target_assign
      • rsqrt
      • RNNCell
      • sampled_softmax_with_cross_entropy
      • SampleEmbeddingHelper
      • sampling_id
      • scale
      • scatter
      • scatter_nd_add
      • scatter_nd
      • selu
      • sequence_concat
      • sequence_conv
      • sequence_enumerate
      • sequence_expand_as
      • sequence_expand
      • sequence_first_step
      • sequence_last_step
      • sequence_mask
      • sequence_pad
      • sequence_pool
      • sequence_reshape
      • sequence_reverse
      • sequence_scatter
      • sequence_slice
      • sequence_softmax
      • sequence_unpad
      • shape
      • shard_index
      • shuffle_channel
      • sigmoid
      • sigmoid_cross_entropy_with_logits
      • sigmoid_focal_loss
      • sign
      • similarity_focus
      • sin
      • size
      • slice
      • smooth_l1
      • soft_relu
      • softmax
      • softmax_with_cross_entropy
      • softplus
      • softshrink
      • softsign
      • space_to_depth
      • spectral_norm
      • split
      • sqrt
      • square
      • square_error_cost
      • squeeze
      • ssd_loss
      • stack
      • stanh
      • StaticRNN
      • strided_slice
      • sum
      • sums
      • swish
      • Switch
      • switch_case
      • t
      • tanh
      • tanh_shrink
      • target_assign
      • teacher_student_sigmoid_loss
      • temporal_shift
      • tensor_array_to_tensor
      • thresholded_relu
      • topk
      • trace
      • transpose
      • TrainingHelper
      • tril
      • triu
      • unfold
      • Uniform
      • uniform_random
      • unique
      • unique_with_counts
      • unsqueeze
      • unstack
      • warpctc
      • where
      • While
      • while_loop
      • yolo_box
      • yolov3_loss
      • zeros
      • zeros_like
    • fluid.metrics
      • Accuracy
      • Auc
      • ChunkEvaluator
      • CompositeMetric
      • DetectionMAP
      • EditDistance
      • MetricBase
      • Precision
      • Recall
    • fluid.nets
      • glu
      • img_conv_group
      • scaled_dot_product_attention
      • sequence_conv_pool
      • simple_img_conv_pool
    • fluid.optimizer
      • Adadelta
      • AdadeltaOptimizer
      • Adagrad
      • AdagradOptimizer
      • Adam
      • Adamax
      • AdamaxOptimizer
      • AdamOptimizer
      • DecayedAdagrad
      • DecayedAdagradOptimizer
      • DGCMomentumOptimizer
      • Dpsgd
      • DpsgdOptimizer
      • ExponentialMovingAverage
      • Ftrl
      • FtrlOptimizer
      • LambOptimizer
      • LarsMomentum
      • LarsMomentumOptimizer
      • LookaheadOptimizer
      • ModelAverage
      • Momentum
      • MomentumOptimizer
      • RecomputeOptimizer
      • RMSPropOptimizer
      • SGD
      • SGDOptimizer
    • fluid.profiler
      • cuda_profiler
      • profiler
      • reset_profiler
      • start_profiler
      • stop_profiler
    • fluid.regularizer
      • L1Decay
      • L1DecayRegularizer
      • L2Decay
      • L2DecayRegularizer
    • fluid.transpiler
      • DistributeTranspiler
      • DistributeTranspilerConfig
      • HashName
      • memory_optimize
      • release_memory
    • fluid.unique_name
      • generate
      • guard
      • switch
  • 常见问题
    • 安装类FAQ
    • 框架类FAQ
    • 其他常见问题
  • Release Note
  • beam_search
    • 参数
    • 返回
    • 返回类型
    • 代码示例
  • »
  • API Reference »
  • fluid.layers »
  • beam_search
  • View page source

beam_search¶

paddle.fluid.layers.beam_search(pre_ids, pre_scores, ids, scores, beam_size, end_id, level=0, is_accumulated=True, name=None, return_parent_idx=False)[源代码]¶

束搜索(Beam search)是在机器翻译等生成任务中选择候选词的一种经典算法

更多细节参考 Beam Search

该OP仅支持LoDTensor,在计算产生得分之后使用,完成单个时间步内的束搜索。具体而言,在计算部分产生 ids 和 scores 后,对于每个源句(样本)该OP从 ids 中根据其对应的 scores 选择当前时间步 top-K (K 是 beam_size)的候选词id。而 pre_id 和 pre_scores 是上一时间步 beam_search 的输出,加入输入用于特殊处理到达结束的翻译候选。

注意,如果 is_accumulated 为 True,传入的 scores 应该是累积分数。反之,scores 是单步得分,会在该OP内被转化为log值并累积到 pre_scores 作为最终得分。如需使用长度惩罚,应在计算累积分数前使用其他OP完成。

束搜索的完整用法请参阅以下示例:

fluid/tests/book/test_machine_translation.py

参数¶

  • pre_ids (Variable) - LoD level为2的LodTensor,表示前一时间步选择的候选id,是前一时间步 beam_search 的输出。第一步时,其形状应为为 \([batch\_size,1]\) , lod应为 \([[0,1,...,batch\_size],[0,1,...,batch\_size]]\) 。数据类型为int64。
  • pre_scores (Variable) - 维度和LoD均与 pre_ids 相同的LodTensor,表示前一时间步所选id对应的累积得分,是前一时间步 beam_search 的输出。数据类型为float32。
  • ids (None|Variable) - 包含候选id的LodTensor。LoD应与 pre_ids 相同,形状为 \([batch\_size \times beam\_size,K]\) ,其中第一维大小与 pre_ids 相同且``batch_size`` 会随样本到达结束而自动减小, K 应该大于 beam_size 。数据类型为int64。可为空,为空时使用 scores 上的索引作为id。
  • scores (Variable) - 表示 ids 对应的累积分数的LodTensor变量, 维度和LoD均与 ids 相同。
  • beam_size (int) - 指明束搜索中的束宽度。
  • end_id (int) - 指明标识序列结束的id。
  • level (int,可选) - 可忽略,当前不能更改 。知道LoD level为2即可,两层lod的意义如下: 第一级表示每个源句(样本)包含的beam大小,若满足结束条件(达到 beam_size 个结束)则变为0;第二级是表示每个beam被选择的次数。
  • is_accumulated (bool,可选) - 指明输入分数 scores 是否为累积分数,默认为True。
  • name (str,可选) – 具体用法请参见 Name ,一般无需设置,默认值为None。
  • return_parent_idx (bool,可选) - 指明是否返回一个额外的Tensor,该Tensor保存了选择的id的父节点(beam)在 pre_id 中索引,可用于通过gather OP更新其他Tensor的内容。默认为False。

返回¶

Variable的二元组或三元组。二元组中包含了当前时间步选择的id和对应的累积得分两个LodTensor,形状相同且均为 \([batch\_size×beam\_size,1]\) ,LoD相同且level均为2,数据类型分别为int64和float32;若 return_parent_idx 为True时为三元组,多返回一个保存了父节点在 pre_id 中索引的Tensor,形状为 \([batch\_size \times beam\_size]\) ,数据类型为int64。

返回类型¶

tuple

代码示例¶

import paddle.fluid as fluid

# 假设 `probs` 包含计算神经元所得的预测结果
# `pre_ids` 和 `pre_scores` 为beam_search之前时间步的输出
beam_size = 4
end_id = 1
pre_ids = fluid.layers.data(
    name='pre_id', shape=[1], lod_level=2, dtype='int64')
pre_scores = fluid.layers.data(
    name='pre_scores', shape=[1], lod_level=2, dtype='float32')
probs = fluid.layers.data(
    name='probs', shape=[10000], dtype='float32')
topk_scores, topk_indices = fluid.layers.topk(probs, k=beam_size)
accu_scores = fluid.layers.elementwise_add(
                                      x=fluid.layers.log(x=topk_scores),
                                      y=fluid.layers.reshape(
                                          pre_scores, shape=[-1]),
                                      axis=0)
selected_ids, selected_scores = fluid.layers.beam_search(
                                      pre_ids=pre_ids,
                                      pre_scores=pre_scores,
                                      ids=topk_indices,
                                      scores=accu_scores,
                                      beam_size=beam_size,
                                      end_id=end_id)