|
from datasets import load_dataset
|
|
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer
|
|
from huggingface_hub import HfApi, Repository, login
|
|
import os
|
|
|
|
|
|
token = os.getenv('HUGGINGFACE_TOKEN')
|
|
if token is None:
|
|
raise ValueError("HUGGINGFACE_TOKEN environment variable not set")
|
|
|
|
login(token=token)
|
|
|
|
|
|
dataset = load_dataset("yelp_review_full")
|
|
|
|
|
|
print(dataset["train"][100])
|
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
|
|
|
|
|
|
def tokenize_function(examples):
|
|
return tokenizer(examples["text"], padding="max_length", truncation=True)
|
|
|
|
|
|
tokenized_datasets = dataset.map(tokenize_function, batched=True)
|
|
|
|
|
|
small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(100))
|
|
small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(100))
|
|
|
|
|
|
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
|
|
|
|
|
|
training_args = TrainingArguments(
|
|
output_dir="./results",
|
|
evaluation_strategy="epoch",
|
|
learning_rate=2e-5,
|
|
per_device_train_batch_size=16,
|
|
per_device_eval_batch_size=16,
|
|
num_train_epochs=3,
|
|
weight_decay=0.01,
|
|
)
|
|
|
|
|
|
trainer = Trainer(
|
|
model=model,
|
|
args=training_args,
|
|
train_dataset=small_train_dataset,
|
|
eval_dataset=small_eval_dataset,
|
|
)
|
|
|
|
|
|
trainer.train()
|
|
|
|
|
|
model_name = "yelp_review_classifier"
|
|
repo_url = HfApi().create_repo(name=model_name, private=False, token=token)
|
|
repo = Repository(local_dir=model_name, clone_from=repo_url)
|
|
|
|
model.save_pretrained(model_name)
|
|
tokenizer.save_pretrained(model_name)
|
|
repo.push_to_hub(commit_message="Initial commit", token=token)
|
|
|