from datasets import load_dataset
dataset = load_dataset("imdb") # Example with IMDB dataset
from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
Load pre-trained model and tokenizer
model_name = "bert-base-uncased"
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertForSequenceClassification.from_pretrained(model_name)
Tokenize the dataset
def tokenize_function(examples):
return tokenizer(examples['text'], padding="max_length", truncation=True)
tokenized_datasets = dataset.map(tokenize_function, batched=True)
Define training arguments
training_args = TrainingArguments(
output_dir="./results",
evaluation_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=16,
num_train_epochs=3,
)
Create Trainer instance
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets["train"],
eval_dataset=tokenized_datasets["test"],
)
Train the model
trainer.train()
model.save_pretrained("./my_model")
tokenizer.save_pretrained("./my_model")
Upload to Hugging Face
from huggingface_hub import HfApi, HfFolder
Log in to your Hugging Face account
HfFolder.save_token("YOUR_HUGGINGFACE_TOKEN")
api = HfApi()
api.upload_folder(
folder_path="./my_model",
path_in_repo="my_model",
repo_id="your_username/my_model",
repo_type="model",
)
from transformers import pipeline
classifier = pipeline("text-classification", model="your_username/my_model")
result = classifier("This is an example sentence.")
print(result)