You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

pipeline.md 2.6 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Pipeline使用教程
  2. 本文简单介绍如何使用`pipeline`函数加载模型进行推理。`pipeline`函数支持按照任务类型、模型名称从模型仓库拉取模型进行进行推理,包含以下几个方面:
  3. * 使用pipeline()函数进行推理
  4. * 指定特定预处理、特定模型进行推理
  5. * 不同场景推理任务示例
  6. ## 环境准备
  7. 详细步骤可以参考 [快速开始](../quick_start.md)
  8. ## Pipeline基本用法
  9. 下面以中文分词任务为例,说明pipeline函数的基本用法
  10. 1. pipeline函数支持指定特定任务名称,加载任务默认模型,创建对应pipeline对象
  11. 执行如下python代码
  12. ```python
  13. from modelscope.pipelines import pipeline
  14. word_segmentation = pipeline('word-segmentation')
  15. ```
  16. 2. 输入文本
  17. ``` python
  18. input = '今天天气不错,适合出去游玩'
  19. print(word_segmentation(input))
  20. {'output': '今天 天气 不错 , 适合 出去 游玩'}
  21. ```
  22. 3. 输入多条样本
  23. pipeline对象也支持传入多个样本列表输入,返回对应输出列表,每个元素对应输入样本的返回结果
  24. ```python
  25. inputs = ['今天天气不错,适合出去游玩','这本书很好,建议你看看']
  26. print(word_segmentation(inputs))
  27. [{'output': '今天 天气 不错 , 适合 出去 游玩'}, {'output': '这 本 书 很 好 , 建议 你 看看'}]
  28. ```
  29. ## 指定预处理、模型进行推理
  30. pipeline函数支持传入实例化的预处理对象、模型对象,从而支持用户在推理过程中定制化预处理、模型。
  31. 1. 首先,创建预处理方法和模型
  32. ```python
  33. from modelscope.models import Model
  34. from modelscope.preprocessors import TokenClassifcationPreprocessor
  35. model = Model.from_pretrained('damo/nlp_structbert_word-segmentation_chinese-base')
  36. tokenizer = TokenClassifcationPreprocessor(model.model_dir)
  37. ```
  38. 2. 使用tokenizer和模型对象创建pipeline
  39. ```python
  40. from modelscope.pipelines import pipeline
  41. word_seg = pipeline('word-segmentation', model=model, preprocessor=tokenizer)
  42. input = '今天天气不错,适合出去游玩'
  43. print(word_seg(input))
  44. {'output': '今天 天气 不错 , 适合 出去 游玩'}
  45. ```
  46. ## 不同场景任务推理示例
  47. 下面以一个图像任务:人像抠图('image-matting')为例,进一步说明pipeline的用法
  48. ```python
  49. import cv2
  50. from modelscope.pipelines import pipeline
  51. img_matting = pipeline('image-matting')
  52. result = img_matting('https://modelscope.oss-cn-beijing.aliyuncs.com/test/images/image_matting.png')
  53. cv2.imwrite('result.png', result['output_png'])
  54. ```