Download script.py from sdyy/autotrain-az2: direct link, hf CLI and curl.
- Browser
- Download file 2.39 kB
-
https://huggingface.co/datasets/sdyy/autotrain-az2/resolve/main/script.py
- Command line
-
hf download hf://datasets/sdyy/autotrain-az2/script.py
-
curl -L -o script.py https://huggingface.co/datasets/sdyy/autotrain-az2/resolve/main/script.py
2.39 kB
| from datasets import load_dataset | |
| from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer | |
| from huggingface_hub import HfApi, Repository, login | |
| import os | |
| # تسجيل الدخول إلى حسابك في Hugging Face باستخدام التوكن من متغير البيئة | |
| 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]) | |
| # تحميل التوكنايزر الخاص بـ BERT | |
| 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)) | |
| # تحميل نموذج BERT المسبق التدريب لتصنيف النصوص | |
| 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() | |
| # رفع النموذج إلى Hugging Face | |
| 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) | |