-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfeature_main.py
141 lines (97 loc) · 5.7 KB
/
feature_main.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
import argparse
import os
from dataset import feature_dataset
import torch
from torch.utils.data import DataLoader
import numpy as np
import pandas as pd
import engine
from utils import Multiclass_classification_metrices
from model import Feature_FC_layer_for_Diet
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--num_classes', default=8, type=int, help=' CRIC:- 8 classes, Breast_Cancer datset :- 8 classes')
parser.add_argument('--feat_dir', default='/path', type=str, help='path to the feature directory')
parser.add_argument('--num_epochs', default=100, type=int, help= 'Number of total training epochs')
parser.add_argument('--model', default='Feature_FC_layer_for_Diet', type=str, help='Model to be used')
parser.add_argument('--batch_size', default=512, type=int, help='Batch size for the dataloader')
parser.add_argument('--num_workers', default=4, type=int, help='num workers for dataloader')
parser.add_argument('--lr', default=0.0002, type=float, help='Initial learning rate')
parser.add_argument('--weight_decay', default=5e-3, type=float, help='Weight Decay')
parser.add_argument('--patience', default=20, type=int, help='Representing the number of consecutive epochs where the performance metric does not improve before training stops')
parser.add_argument('--folds', default=5, type=int, help='No of folds in K-folds')
parser.add_argument('--loss', default='cross_entropy', type=str, help='Loss :- 1)cross_entropy 2)hinge_loss')
parser.add_argument('--dataset', default='Breast_cancer', type=str, help='dataset :- 1)Breast_cancer 2)Cervical_cancer')
parser.add_argument('--metric', default='class_Overlap_metric', type=str, help='metric :- 1)class_Overlap_metric 2)confusion_set_Overlap_metric 3)expt2')
parser.add_argument('--distance_in_hinge_loss', default=5, type=float, help='distance_in_hinge_loss')
args = parser.parse_args()
path = '/kaggle/working/'
#path = '/kaggle/input/cp-label-5fold-dataset/CP_dataset/'
df_feature = pd.read_csv(args.feat_dir)
for fold in range(args.folds):
print(f'folde :- {fold}')
train = str(fold) + 'train.csv'
train_path = os.path.join(path, 'Train_Val_split', train)
df_train = pd.read_csv(train_path)
train_dataset = feature_dataset(df_feature = df_feature, df_label = df_train)
train_loader = DataLoader(train_dataset, batch_size = args.batch_size, shuffle = True, num_workers = args.num_workers)
val = str(fold) + 'val.csv'
val_path = os.path.join(path, 'Train_Val_split', val)
df_val = pd.read_csv(val_path)
val_dataset = feature_dataset(df_feature = df_feature, df_label = df_val)
val_loader = DataLoader(val_dataset, batch_size = args.batch_size, shuffle = True, num_workers = args.num_workers)
test_path = os.path.join(path, 'Test', 'test.csv')
df_test = pd.read_csv(test_path)
test_dataset = feature_dataset(df_feature = df_feature, df_label = df_test)
test_loader = DataLoader(test_dataset, batch_size = args.batch_size, shuffle = True, num_workers = args.num_workers)
# model :-
if args.model == 'Feature_FC_layer_for_Diet':
model = Feature_FC_layer_for_Diet(args.num_classes)
device = torch.device("cuda")
model.to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, betas=(0.5, 0.99))
patience = args.patience
best_val_loss = np.inf
epochs_without_improvement = 0
best_model_state = None
for epoch in range(args.num_epochs):
print(f'epoch :-{epoch}')
engine.train(train_loader, model, optimizer, args.loss, args.dataset, args.metric, args.distance_in_hinge_loss)
_, _, val_loss= engine.val(val_loader, model, args.loss, args.dataset, args.metric, args.distance_in_hinge_loss)
print(f'val_loss:-{val_loss}')
# early stopping :-
if epoch>=10:
if val_loss < best_val_loss:
best_val_loss = val_loss
epochs_without_improvement = 0
# Save the state dictionary of the best model
best_model_state = model.state_dict()
else:
epochs_without_improvement += 1
if epochs_without_improvement >= patience:
print(f"Early stopping after {epoch+1} epochs without improvement.")
break
# Load the best model state dictionary for val metrices :-
if best_model_state is not None:
model.load_state_dict(best_model_state)
print()
print('val')
val_predictions, val_labels, _ = engine.val(val_loader, model, args.loss, args.dataset, args.metric, args.distance_in_hinge_loss)
val_auc, val_acc = Multiclass_classification_metrices(val_labels, val_predictions, args.num_classes)
print(f'val_auc:-{val_auc}')
print(f'val_acc:-{val_acc}')
print()
print()
print('test')
test_predictions, test_labels, softmax_values_list, df_combined = engine.test(test_loader, model)
if args.loss == 'hinge_loss':
output = str(args.distance_in_hinge_loss) + '_' + str(fold) + '_' + 'softmax_output.csv'
else:
output = str(fold) + 'softmax_output.csv'
df_combined.to_csv(os.path.join('/kaggle/working/', output), index=False)
test_auc, test_acc = Multiclass_classification_metrices(test_labels, test_predictions, args.num_classes)
print(f'test_auc:-{test_auc}')
print(f'test_acc:-{test_acc}')
print()
if __name__ == '__main__':
main()