Lesson 9 of 12 · 2 min
Hugging Face Transformers Library
The standard library for using pre-trained language models.
from transformers import pipeline
# Zero-shot text generation (GPT-2)
generator = pipeline('text-generation', model='gpt2')
result = generator('The future of AI is', max_new_tokens=50)
print(result[0]['generated_text'])
# Output: [{'generated_text': 'The future of AI is bright and full of potential...'}]
# Sentiment analysis
sentiment = pipeline('sentiment-analysis')
print(sentiment('I absolutely love this!'))
# Output: [{'label': 'POSITIVE', 'score': 0.9998}]
# Summarisation (Flan-T5)
summariser = pipeline('summarization', model='google/flan-t5-base')
text = "Artificial intelligence has revolutionised..."
print(summariser(text, max_length=60, min_length=20))
# Output: [{'summary_text': 'AI is transforming industries...'}]
# Translation
translator = pipeline('translation_en_to_fr', model='Helsinki-NLP/opus-mt-en-fr')
print(translator('Hello, how are you?'))
# Q&A
qa = pipeline('question-answering')
print(qa(question='What is the capital of France?', context='Paris is the capital of France.'))
# Output: {'answer': 'Hugging Face', 'score': 0.9821, 'start': 32, 'end': 44}