i want to use hugging face pretrained models in my project , how ?
- User
i want to use hugging face pretrained models in my project , how ?
- Assistant
i want to use hugging face pretrained models in my project , how ?
Using Hugging Face pretrained models in your project is straightforward thanks to the transformers library, which provides easy access to a wide range of models for tasks like text classification, translation, summarization, question answering, and more.
Here’s a step-by-step guide to get you started:
transformers libraryYou can install it using pip:
pip install transformers
If you also want to use PyTorch or TensorFlow as your backend, make sure you have one of them installed:
pip install torch
pip install tensorflow
Models usually need tokenizers to convert text into the format the model understands.
Example: Using the bert-base-uncased model for text classification or feature extraction.
from transformers import AutoTokenizer, AutoModel
# Choose a model name (you can find many on https://huggingface.co/models)
model_name = "bert-base-uncased"
# Load pretrained tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)
# Example input
text = "Hello, Hugging Face!"
# Tokenize input
inputs = tokenizer(text, return_tensors="pt") # use return_tensors="tf" for TensorFlow
# Get model outputs
outputs = model(**inputs)
# The outputs contain hidden states, etc.
print(outputs.last_hidden_state.shape)
Some tasks have specific classes, for example:
from transformers import pipeline
classifier = pipeline("sentiment-analysis")
result = classifier("I love using Hugging Face models!")
print(result)
from transformers import pipeline
qa_pipeline = pipeline("question-answering")
result = qa_pipeline({
'question': "What is Hugging Face?",
'context': "Hugging Face is a company that provides machine learning models and datasets."
})
print(result)
from transformers import pipeline
generator = pipeline("text-generation", model="gpt2")
result = generator("Once upon a time,", max_length=30)
print(result)
Visit https://huggingface.co/models to browse available models. You can plug the model name into the above code to try different pretrained models.
After fine-tuning a model, you can save it locally:
model.save_pretrained("./my_model")
tokenizer.save_pretrained("./my_model")
And load it later:
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("./my_model")
model = AutoModel.from_pretrained("./my_model")
If you tell me what specific task or framework you want to integrate with, I can provide more tailored code snippets.
Not yet included in a published release.