-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
150 lines (115 loc) · 4.78 KB
/
test.py
File metadata and controls
150 lines (115 loc) · 4.78 KB
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
import os
import yaml
import pandas as pd
import glob
from pathlib import Path
import logging
from typing import List, Tuple
import torch
import numpy as np
from sklearn.model_selection import train_test_split
from transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
Trainer,
TrainingArguments
)
from .src.Utils import get_dataset_files, load_and_preprocess_dataset, get_training_args
from .src.dataset import create_datasets
from .src.metrics import compute_metrics, plot_confusion_matrix
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# testing individual datasets
def test_individual(config: dict):
"""Test the model one by one on multiple datasets."""
try:
dataset_files = get_dataset_files(config['data']['data_dir'], logger)
# Load the model
model = AutoModelForSequenceClassification.from_pretrained(config['testing']['trained_model_path'])
# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
# traverse through each datasets
for file_path in dataset_files:
dataset_name = Path(file_path).stem
logger.info(f"\nStarting training on dataset: {dataset_name}")
# Create dataset-specific output directories
test_results_dir = os.path.join(config['testing']['individual_save_dir'], dataset_name)
# Load and preprocess current dataset
df = load_and_preprocess_dataset(file_path, logger)
_, test_dataset = create_datasets(df, config, logger, 'testing')
training_args = get_training_args(config, test_results_dir)
# Initialize Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=_,
eval_dataset=test_dataset,
compute_metrics=compute_metrics
)
# Save model and evaluation results
trainer.evaluate()
# Save evaluation results
plot_confusion_matrix(
test_dataset,
trainer,
os.path.join(test_results_dir, 'confusion_matrix.png')
)
except Exception as e:
logger.error(f"Individual testing failed: {str(e)}")
raise
# trainning on all datasets combined
def test_combined(config: dict):
"""Test on test set from all datasets combined."""
try:
dataset_files = get_dataset_files(config['data']['data_dir'], logger)
# Combine all datasets
dfs = []
for file_path in dataset_files:
df = load_and_preprocess_dataset(file_path, logger)
dfs.append(df)
combined_df = pd.concat(dfs, ignore_index=True).sample(frac=1).reset_index(drop=True)
# Create combined dataset
_, test_dataset = create_datasets(combined_df, config, logger, 'testing')
# Load the model
model = AutoModelForSequenceClassification.from_pretrained(config['testing']['trained_model_path'])
# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
training_args = get_training_args(config, None)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=_,
eval_dataset=test_dataset,
compute_metrics=compute_metrics
)
# Evaluate the model
trainer.evaluate()
# Save evaluation results
plot_confusion_matrix(
test_dataset,
trainer,
'results/test_results/confusion_matrix.png'
)
except Exception as e:
logger.error(f"Combined testing failed: {str(e)}")
raise
# Main function to load config and start training
def main():
try:
# Load config
with open('configs/model_config.yaml', 'r') as f:
config = yaml.safe_load(f)
# Create base output directories
os.makedirs(config['testing']['results_path'], exist_ok=True)
os.makedirs(config['testing']['logs_path'], exist_ok=True)
if config['testing']['inference_scheme'] == 'individual':
test_individual(config)
else:
test_combined(config)
except Exception as e:
logger.error(f"Testing failed: {str(e)}")
raise
if __name__ == "__main__":
main()