maxxcarl commited on
Commit
f4fd89b
Β·
1 Parent(s): a671e97

Upload KAGGLE_NOTEBOOK.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. KAGGLE_NOTEBOOK.md +191 -0
KAGGLE_NOTEBOOK.md ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🎡 Spotify Genre Classifier - Kaggle Notebook
2
+
3
+ ## Cell 1: Install Dependencies
4
+ ```python
5
+ !pip install -q transformers datasets accelerate evaluate scikit-learn python-dotenv tqdm
6
+ ```
7
+
8
+ ## Cell 2: Import and Setup Secrets
9
+ ```python
10
+ from kaggle_secrets import UserSecretsClient
11
+ import os
12
+
13
+ # Get secrets from Kaggle
14
+ user_secrets = UserSecretsClient()
15
+ os.environ['HF_TOKEN'] = user_secrets.get_secret("HF_TOKEN")
16
+ os.environ['HF_USERNAME'] = user_secrets.get_secret("HF_USERNAME")
17
+
18
+ print(f"βœ“ Logged in as: {os.environ['HF_USERNAME']}")
19
+ ```
20
+
21
+ ## Cell 3: Check GPU
22
+ ```python
23
+ import torch
24
+
25
+ if torch.cuda.is_available():
26
+ print(f"βœ“ GPU Available: {torch.cuda.get_device_name(0)}")
27
+ print(f" GPU Count: {torch.cuda.device_count()}")
28
+ else:
29
+ print("⚠ No GPU - using CPU (slower)")
30
+ ```
31
+
32
+ ## Cell 4: Load Dataset
33
+ ```python
34
+ from datasets import load_dataset
35
+
36
+ print("πŸ“Š Loading dataset...")
37
+ dataset = load_dataset("maharshipandya/spotify-tracks-dataset")
38
+ print(f"βœ“ Loaded {len(dataset['train'])} tracks")
39
+ ```
40
+
41
+ ## Cell 5: Load Model
42
+ ```python
43
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
44
+
45
+ model_name = "gpt2"
46
+ print(f"πŸ€– Loading model: {model_name}")
47
+
48
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
49
+ if tokenizer.pad_token is None:
50
+ tokenizer.pad_token = tokenizer.eos_token
51
+
52
+ # Get unique genres
53
+ genres = sorted(set(dataset['train']['track_genre']))
54
+ num_labels = len(genres)
55
+ label2id = {g: i for i, g in enumerate(genres)}
56
+ id2label = {i: g for i, g in enumerate(genres)}
57
+
58
+ model = AutoModelForSequenceClassification.from_pretrained(
59
+ model_name,
60
+ num_labels=num_labels,
61
+ id2label=id2label,
62
+ label2id=label2id
63
+ )
64
+
65
+ print(f"βœ“ Model loaded: {num_labels} genres")
66
+ ```
67
+
68
+ ## Cell 6: Preprocess Data
69
+ ```python
70
+ def tokenize(ex):
71
+ texts = [str(t) if t else "" for t in ex['track_name']]
72
+ tokenized = tokenizer(texts, padding='max_length', truncation=True, max_length=128)
73
+ tokenized['labels'] = [label2id[l] for l in ex['track_genre']]
74
+ return tokenized
75
+
76
+ print("πŸ”§ Preprocessing...")
77
+ tokenized_dataset = dataset.map(tokenize, batched=True, remove_columns=dataset['train'].column_names)
78
+
79
+ # Create validation split
80
+ splits = tokenized_dataset['train'].train_test_split(test_size=0.1)
81
+ tokenized_dataset = {
82
+ 'train': splits['train'],
83
+ 'validation': splits['test']
84
+ }
85
+
86
+ print(f"βœ“ Train: {len(tokenized_dataset['train'])}, Val: {len(tokenized_dataset['validation'])}")
87
+ ```
88
+
89
+ ## Cell 7: Training
90
+ ```python
91
+ from transformers import TrainingArguments, Trainer
92
+ import numpy as np
93
+ import evaluate
94
+
95
+ # Metrics
96
+ def compute_metrics(eval_pred):
97
+ predictions = np.argmax(eval_pred.predictions, axis=1)
98
+ accuracy = evaluate.load("accuracy")
99
+ f1 = evaluate.load("f1")
100
+ return {
101
+ 'accuracy': accuracy.compute(predictions=predictions, references=eval_pred.label_ids)['accuracy'],
102
+ 'f1_macro': f1.compute(predictions=predictions, references=eval_pred.label_ids, average='macro')['f1']
103
+ }
104
+
105
+ # Training args
106
+ training_args = TrainingArguments(
107
+ output_dir="./model",
108
+ num_train_epochs=3,
109
+ per_device_train_batch_size=16,
110
+ per_device_eval_batch_size=32,
111
+ learning_rate=5e-5,
112
+ fp16=True, # Use mixed precision on GPU
113
+ eval_strategy="epoch",
114
+ save_strategy="epoch",
115
+ load_best_model_at_end=True,
116
+ logging_steps=50,
117
+ report_to="none"
118
+ )
119
+
120
+ # Trainer
121
+ trainer = Trainer(
122
+ model=model,
123
+ args=training_args,
124
+ train_dataset=tokenized_dataset['train'],
125
+ eval_dataset=tokenized_dataset['validation'],
126
+ processing_class=tokenizer,
127
+ compute_metrics=compute_metrics
128
+ )
129
+
130
+ print("πŸš€ Starting training...")
131
+ trainer.train()
132
+ print("βœ“ Training complete!")
133
+ ```
134
+
135
+ ## Cell 8: Evaluate
136
+ ```python
137
+ print("πŸ“ˆ Evaluating...")
138
+ metrics = trainer.evaluate()
139
+ print(f"Final Accuracy: {metrics['eval_accuracy']:.4f}")
140
+ print(f"Final F1: {metrics['eval_f1_macro']:.4f}")
141
+ ```
142
+
143
+ ## Cell 9: Save Model
144
+ ```python
145
+ model.save_pretrained("./final_model")
146
+ tokenizer.save_pretrained("./final_model")
147
+ print("πŸ’Ύ Model saved to ./final_model")
148
+ ```
149
+
150
+ ## Cell 10: Test Predictions
151
+ ```python
152
+ import torch
153
+
154
+ test_tracks = [
155
+ "Bohemian Rhapsody",
156
+ "Shape of You",
157
+ "Old Town Road",
158
+ "Blinding Lights",
159
+ "Bad Guy"
160
+ ]
161
+
162
+ model.eval()
163
+ print("\n🎡 Predictions:")
164
+ for track in test_tracks:
165
+ inputs = tokenizer(track, return_tensors='pt', truncation=True, max_length=128)
166
+ if torch.cuda.is_available():
167
+ inputs = {k: v.cuda() for k, v in inputs.items()}
168
+
169
+ with torch.no_grad():
170
+ outputs = model(**inputs)
171
+ pred_id = torch.argmax(outputs.logits, dim=-1).item()
172
+ conf = torch.softmax(outputs.logits, dim=-1)[0, pred_id].item()
173
+
174
+ print(f" '{track}' β†’ {id2label[pred_id]} ({conf:.2%})")
175
+ ```
176
+
177
+ ## Cell 11: Push to Hub (Optional)
178
+ ```python
179
+ from huggingface_hub import login
180
+
181
+ hf_token = os.environ['HF_TOKEN']
182
+ username = os.environ['HF_USERNAME']
183
+
184
+ login(token=hf_token)
185
+
186
+ repo_name = "spotify-genre-classifier"
187
+ model.push_to_hub(f"{username}/{repo_name}")
188
+ tokenizer.push_to_hub(f"{username}/{repo_name}")
189
+
190
+ print(f"βœ… Model pushed to: https://huggingface.co/{username}/{repo_name}")
191
+ ```