-
Notifications
You must be signed in to change notification settings - Fork 0
/
BERT.py
663 lines (509 loc) · 21.3 KB
/
BERT.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
# -*- coding: utf-8 -*-
"""Assignment-3-BERTipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1IfWQGKl9bYVWijV6Wd-Z_Nolm5PC2iYr
"""
pip install transformers[torch] datasets
from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset, random_split
from datasets import load_dataset
#sadness (0), joy (1), love (2), anger (3), fear (4), surprise (5).
# Replace 'emotion' with the name of the emotion dataset you want to load
dataset_name = 'emotion'
# Load the emotion dataset
emotion_dataset = load_dataset(dataset_name)
# Access the train split of the dataset
train_dataset = emotion_dataset['train']
test_dataset = emotion_dataset['test']
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
# Access the text and label columns from the train split
emotion_train_texts = train_dataset['text']
emotion_train_labels = train_dataset['label']
# Access the text and label columns from the test split
emotion_test_texts = test_dataset['text']
emotion_test_labels = test_dataset['label']
# Create a pipeline with CountVectorizer and Multinomial Naive Bayes
nb_pipeline = make_pipeline(CountVectorizer(), MultinomialNB())
# Fit the pipeline on the training data
nb_pipeline.fit(emotion_train_texts, emotion_train_labels)
# Predict on the test data
nb_predictions = nb_pipeline.predict(emotion_test_texts)
# Evaluate the Naive Bayes model
nb_accuracy = accuracy_score(emotion_test_labels, nb_predictions)
print("Naive Bayes Accuracy:", nb_accuracy)
# Additional evaluation metrics
print("\nClassification Report:\n", classification_report(emotion_test_labels, nb_predictions))
print("\nConfusion Matrix:\n", confusion_matrix(emotion_test_labels, nb_predictions))
from transformers import BertTokenizer, BertForSequenceClassification
from torch.utils.data import DataLoader
import torch
# Load BERT tokenizer and model
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForSequenceClassification.from_pretrained('bert-base-uncased')
# Tokenize and convert tokens into numerical features
def tokenize_and_convert_to_features(texts, labels, max_length=128):
tokenized_data = tokenizer(texts, truncation=True, padding=True, max_length=max_length, return_tensors='pt')
input_ids = tokenized_data['input_ids']
attention_mask = tokenized_data['attention_mask']
labels = torch.tensor(labels)
return input_ids, attention_mask, labels
# Tokenize and convert the training data
input_ids_train, attention_mask_train, labels_train = tokenize_and_convert_to_features(emotion_train_texts, emotion_train_labels)
# Tokenize and convert the test data
input_ids_test, attention_mask_test, labels_test = tokenize_and_convert_to_features(emotion_test_texts, emotion_test_labels)
# Create DataLoader for training and test data
train_data = list(zip(input_ids_train, attention_mask_train, labels_train))
train_loader = DataLoader(train_data, batch_size=32, shuffle=True)
test_data = list(zip(input_ids_test, attention_mask_test, labels_test))
test_loader = DataLoader(test_data, batch_size=32, shuffle=False)
# Training and evaluation using BERT is typically done using a deep learning framework (e.g., PyTorch or TensorFlow)
# You may need to write additional code for training and evaluation based on your specific requirements.
# This example provides a basic setup for tokenization and data loading using transformers.
from sklearn.feature_extraction.text import CountVectorizer
import matplotlib.pyplot as plt
import seaborn as sns
from wordcloud import WordCloud
from textblob import TextBlob
import pandas as pd
# N-gram distribution analysis
def ngram_distribution_analysis(texts, n=2):
vectorizer = CountVectorizer(ngram_range=(n, n))
ngrams = vectorizer.fit_transform(texts)
ngrams_sum = ngrams.sum(axis=0)
ngram_freq = [(word, ngrams_sum[0, idx]) for word, idx in vectorizer.vocabulary_.items()]
ngram_freq = sorted(ngram_freq, key=lambda x: x[1], reverse=True)
return ngram_freq
# Detailed visualization for unigrams and bigrams
def visualize_ngram_distributions(texts, n=2, top_n=20):
ngram_freq = ngram_distribution_analysis(texts, n)
df_ngrams = pd.DataFrame(ngram_freq, columns=[f'{n}-gram', 'Frequency'])
# Bar plot
plt.figure(figsize=(12, 6))
sns.barplot(x='Frequency', y=f'{n}-gram', data=df_ngrams.head(top_n))
plt.title(f'Top {top_n} {n}-grams Distribution')
plt.xlabel('Frequency')
plt.ylabel(f'{n}-gram')
plt.show()
# Word cloud
text_combined = ' '.join(texts)
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text_combined)
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title(f'{n}-gram Word Cloud')
plt.show()
# Example usage for unigrams (n=1)
visualize_ngram_distributions(emotion_train_texts, n=1)
# Example usage for bigrams (n=2)
visualize_ngram_distributions(emotion_train_texts, n=2)
# Visualize dataset information
def visualize_dataset_info(dataset):
plt.figure(figsize=(8, 5))
sns.countplot(x=dataset['label'])
plt.title('Dataset Information')
plt.xlabel('Emotion Class')
plt.ylabel('Count')
plt.show()
# Example usage for dataset information
visualize_dataset_info(train_dataset)
"""Fine-tuning last few layers of Pre-trained BERT Model"""
from sklearn.metrics import precision_recall_fscore_support, accuracy_score
def compute_metrics(pred):
labels = pred.label_ids
logits = pred.predictions[0] # Extract logits
preds = logits.argmax(-1)
precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='weighted')
acc = accuracy_score(labels, preds)
return {
'accuracy': acc,
'f1': f1,
'precision': precision,
'recall': recall
}
# Load the dataset
dataset = load_dataset('emotion')
# Initialize the tokenizer
tokenizer = BertTokenizer.from_pretrained('bhadresh-savani/bert-base-uncased-emotion')
# Function to tokenize the data
def tokenize_function(examples):
return tokenizer(examples['text'], padding='max_length', truncation=True, max_length=64)
# Apply tokenization to all splits
tokenized_datasets = dataset.map(tokenize_function, batched=True)
# Load BERT model
model = BertForSequenceClassification.from_pretrained(
'bhadresh-savani/bert-base-uncased-emotion',
num_labels=len(dataset['train'].features['label'].names),
output_attentions=True,
output_hidden_states=False,
)
# Freeze all the parameters
for param in model.base_model.parameters():
param.requires_grad = False
# Unfreeze the last few layers
for param in model.base_model.encoder.layer[-2:].parameters():
param.requires_grad = True
# Training Arguments
training_args = TrainingArguments(
output_dir='./results',
num_train_epochs=3,
per_device_train_batch_size=32,
warmup_steps=500,
weight_decay=0.01,
logging_dir='./logs',
logging_steps=10,
)
# Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets['train'],
compute_metrics=compute_metrics,
)
# Train the model
trainer.train()
#train_results = trainer.evaluate(tokenized_datasets['train'])
#print(train_results)
import numpy as np
predictions=trainer.predict(tokenized_datasets['test'])
predicted_labels = np.argmax(predictions.predictions[0], axis=-1)
actual_labels = predictions.label_ids
correctly_predicted_docs = []
incorrectly_predicted_docs = []
for i in range(len(actual_labels)):
if predicted_labels[i] == actual_labels[i]:
correctly_predicted_docs.append(dataset['test']['text'][i])
else:
incorrectly_predicted_docs.append(dataset['test']['text'][i])
inputs = tokenizer(correctly_predicted_docs[0], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 3
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
inputs = tokenizer(correctly_predicted_docs[0], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 6
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
inputs = tokenizer(correctly_predicted_docs[0], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 9
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
inputs = tokenizer(incorrectly_predicted_docs[0], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 3
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
inputs = tokenizer(correctly_predicted_docs[0], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 6
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
inputs = tokenizer(correctly_predicted_docs[0], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 9
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
trainer.evaluate(tokenized_datasets['test'])
"""ALL Layers Fine-tuning of BERT Model"""
from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset
from sklearn.metrics import precision_recall_fscore_support, accuracy_score
def compute_metrics(pred):
labels = pred.label_ids
logits = pred.predictions[0] # Extract logits
preds = logits.argmax(-1)
precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='weighted')
acc = accuracy_score(labels, preds)
return {
'accuracy': acc,
'f1': f1,
'precision': precision,
'recall': recall
}
# Load the dataset
dataset = load_dataset('emotion')
# Initialize the tokenizer
tokenizer = BertTokenizer.from_pretrained('bhadresh-savani/bert-base-uncased-emotion')
# Function to tokenize the data
def tokenize_function(examples):
return tokenizer(examples['text'], padding='max_length', truncation=True, max_length=64)
# Apply tokenization to all splits
tokenized_datasets = dataset.map(tokenize_function, batched=True)
# Load BERT model
model = BertForSequenceClassification.from_pretrained(
'bhadresh-savani/bert-base-uncased-emotion',
num_labels=len(dataset['train'].features['label'].names),
output_attentions=True,
output_hidden_states=False,
)
# Unfreeze all the parameters
for param in model.base_model.parameters():
param.requires_grad = True
# Training Arguments
training_args = TrainingArguments(
output_dir='./results',
num_train_epochs=3,
per_device_train_batch_size=32,
warmup_steps=500,
weight_decay=0.01,
logging_dir='./logs',
logging_steps=10,
)
# Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets['train'],
compute_metrics=compute_metrics,
)
# Train the model
trainer.train()
#train_results = trainer.evaluate(tokenized_datasets['train'])
#print(train_results)
import numpy as np
predictions=trainer.predict(tokenized_datasets['test'])
predicted_labels = np.argmax(predictions.predictions[0], axis=-1)
actual_labels = predictions.label_ids
correctly_predicted_docs = []
incorrectly_predicted_docs = []
for i in range(len(actual_labels)):
if predicted_labels[i] == actual_labels[i]:
correctly_predicted_docs.append(dataset['test']['text'][i])
else:
incorrectly_predicted_docs.append(dataset['test']['text'][i])
inputs = tokenizer(correctly_predicted_docs[1], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 3
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
inputs = tokenizer(correctly_predicted_docs[1], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 6
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
inputs = tokenizer(correctly_predicted_docs[1], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 9
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
inputs = tokenizer(incorrectly_predicted_docs[1], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 3
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
inputs = tokenizer(incorrectly_predicted_docs[1], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 6
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
inputs = tokenizer(incorrectly_predicted_docs[1], return_tensors="pt", max_length=64, padding=True, truncation=True)
outputs = model(**inputs.to("cuda"))
attention = outputs[-1] # The attentions are the last output of the model
import matplotlib.pyplot as plt
import seaborn as sns
# Choose which layer and head to visualize
layer = 9
head = 0
# Get the attention weights for the specified layer and head
attention_weights = attention[layer][0, head].cpu().detach().numpy()
# Set up labels for each token
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Plot
plt.figure(figsize=(10, 10))
sns.heatmap(attention_weights, xticklabels=tokens, yticklabels=tokens, square=True)
plt.title(f'Attention Weights - Layer {layer + 1}, Head {head + 1}')
plt.show()
trainer.evaluate(tokenized_datasets['test'])
"""Evaluation on Pre-trained BERT Model"""
from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset
from sklearn.metrics import precision_recall_fscore_support, accuracy_score
def compute_metrics(pred):
labels = pred.label_ids
logits = pred.predictions[0] # Extract logits
preds = logits.argmax(-1)
precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='weighted')
acc = accuracy_score(labels, preds)
return {
'accuracy': acc,
'f1': f1,
'precision': precision,
'recall': recall
}
# Load the dataset
dataset = load_dataset('emotion')
# Initialize the tokenizer
tokenizer = BertTokenizer.from_pretrained('bhadresh-savani/bert-base-uncased-emotion')
# Function to tokenize the data
def tokenize_function(examples):
return tokenizer(examples['text'], padding='max_length', truncation=True, max_length=64)
# Apply tokenization to all splits
tokenized_datasets = dataset.map(tokenize_function, batched=True)
# Load BERT model
model = BertForSequenceClassification.from_pretrained(
'bhadresh-savani/bert-base-uncased-emotion',
num_labels=len(dataset['train'].features['label'].names),
output_attentions=True,
output_hidden_states=False,
)
# Unfreeze all the parameters
for param in model.base_model.parameters():
param.requires_grad = False
# Training Arguments
training_args = TrainingArguments(
output_dir='./results',
num_train_epochs=3,
per_device_train_batch_size=32,
warmup_steps=500,
weight_decay=0.01,
logging_dir='./logs',
logging_steps=10,
)
# Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets['train'],
compute_metrics=compute_metrics,
)
train_results = trainer.evaluate(tokenized_datasets['test'])
print(train_results)