# 1. 情感分析(文本分类)
classifier = pipeline("sentiment-analysis")
result = classifier("I love using Hugging Face Transformers!") # -> [{'label': 'POSITIVE', 'score': 0.9998}]
# 2. 文本生成
generator = pipeline("text-generation", model="gpt2")
result = generator("Once upon a time in a land far away,",
max_new_tokens=50, num_return_sequences=1, temperature=0.8)
# 3. 填空(掩码语言模型)
unmasker = pipeline("fill-mask", model="bert-base-uncased")
result = unmasker("The capital of France is [MASK].") # -> [{'token_str': 'paris', 'score': 0.9823}, ...]
# 4. 命名实体识别(NER)
ner = pipeline("ner", aggregation_strategy="simple")
result = ner("My name is John and I work at Google in New York.") # -> [{'entity_group': 'PER', 'word': 'John', 'score': 0.998}, ...]
# 5. 抽取式问答
qa = pipeline("question-answering")
result = qa(question="Who invented Python?",
context="Python was created by Guido van Rossum in 1991.") # -> {'answer': 'Guido van Rossum', 'score': 0.9887}
# 7. 机器翻译
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-zh")
result = translator("Hello, how are you today?") # -> [{'translation_text': '你好,你今天怎么样?'}]
# 8. 零样本分类(不需要专门训练)
zero_shot = pipeline("zero-shot-classification")
result = zero_shot("I love playing football",
candidate_labels=["sports","politics","technology"]) # -> {'labels': ['sports', ...], 'scores': [0.972, ...]}
ner = pipeline("ner", model="dslim/bert-base-NER", aggregation_strategy="simple")
result = ner("Elon Musk founded SpaceX in 2002 and Tesla Motors in 2003.") for entity in result: print(f"{entity['word']:<20} -> {entity['entity_group']} ({entity['score']:.3f})")
# 中文 NER
ner_cn = pipeline("ner", model="hfl/chinese-bert-wwm-ext-ner-msra",
aggregation_strategy="simple")
result = ner_cn("小明在北京大学读书,后来去了阿里巴巴工作。")
机器翻译
实例
from transformers import pipeline
# 英译中
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-zh")
result = translator("Artificial intelligence is transforming the world.") print(result[0]["translation_text"])# -> 人工智能正在改变世界。
# 中译英
translator_zh = pipeline("translation", model="Helsinki-NLP/opus-mt-zh-en")
result = translator_zh("人工智能正在改变世界。") print(result[0]["translation_text"])