Spaces:
No application file
No application file
Create train.py
Browse files
train.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Import necessary libraries
|
| 2 |
+
from datasets import load_dataset
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
|
| 4 |
+
|
| 5 |
+
# Load your dataset (assuming you uploaded it to Hugging Face)
|
| 6 |
+
dataset = load_dataset("your_dataset_name")
|
| 7 |
+
|
| 8 |
+
# Load pre-trained mBERT tokenizer and model
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained('bert-base-multilingual-cased')
|
| 10 |
+
model = AutoModelForSequenceClassification.from_pretrained('bert-base-multilingual-cased', num_labels=2)
|
| 11 |
+
|
| 12 |
+
# Tokenize the dataset (adjust based on your dataset's structure)
|
| 13 |
+
def tokenize_function(examples):
|
| 14 |
+
return tokenizer(examples['Text'], padding="max_length", truncation=True)
|
| 15 |
+
|
| 16 |
+
# Tokenize the datasets
|
| 17 |
+
tokenized_datasets = dataset.map(tokenize_function, batched=True)
|
| 18 |
+
|
| 19 |
+
# Split into train and test datasets (if not already split)
|
| 20 |
+
train_dataset = tokenized_datasets['train']
|
| 21 |
+
test_dataset = tokenized_datasets['test']
|
| 22 |
+
|
| 23 |
+
# Define training arguments
|
| 24 |
+
training_args = TrainingArguments(
|
| 25 |
+
output_dir='./results', # output directory for model checkpoints
|
| 26 |
+
evaluation_strategy="epoch", # evaluate after each epoch
|
| 27 |
+
learning_rate=2e-5, # learning rate
|
| 28 |
+
per_device_train_batch_size=16, # batch size for training
|
| 29 |
+
per_device_eval_batch_size=64, # batch size for evaluation
|
| 30 |
+
num_train_epochs=3, # number of epochs
|
| 31 |
+
weight_decay=0.01, # strength of weight decay
|
| 32 |
+
logging_dir='./logs', # directory to store logs
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# Initialize Trainer
|
| 36 |
+
trainer = Trainer(
|
| 37 |
+
model=model, # the model to be trained
|
| 38 |
+
args=training_args, # training arguments
|
| 39 |
+
train_dataset=train_dataset, # training dataset
|
| 40 |
+
eval_dataset=test_dataset # evaluation dataset
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# Train the model
|
| 44 |
+
trainer.train()
|
| 45 |
+
|
| 46 |
+
# Save the model to Hugging Face Model Hub
|
| 47 |
+
model.push_to_hub("your_model_name")
|
| 48 |
+
tokenizer.push_to_hub("your_model_name")
|