CoffeBank commited on
Commit
20e51d1
·
1 Parent(s): 441466c
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__/model_utils.cpython-310.pyc
2
+ demo/__pycache__/binary_classifier_demo.cpython-310.pyc
NN_classifier/simple_binary_classifier.py ADDED
@@ -0,0 +1,897 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.optim as optim
6
+ from torch.utils.data import DataLoader, TensorDataset
7
+ from sklearn.model_selection import StratifiedKFold
8
+ from sklearn.metrics import classification_report, accuracy_score, roc_auc_score, precision_recall_fscore_support, confusion_matrix
9
+ from sklearn.preprocessing import StandardScaler, LabelEncoder
10
+ from sklearn.impute import SimpleImputer
11
+ import matplotlib.pyplot as plt
12
+ import json
13
+ import joblib
14
+ import os
15
+ import seaborn as sns
16
+ from scipy import stats
17
+ import time
18
+ import argparse
19
+
20
+ def setup_gpu():
21
+ if torch.cuda.is_available():
22
+ return True
23
+ else:
24
+ print("No GPUs found. Using CPU.")
25
+ return False
26
+
27
+ GPU_AVAILABLE = setup_gpu()
28
+ DEVICE = torch.device('cuda' if GPU_AVAILABLE else 'cpu')
29
+
30
+ def load_data_from_json(directory_path):
31
+ if os.path.isfile(directory_path):
32
+ directory = os.path.dirname(directory_path)
33
+ else:
34
+ directory = directory_path
35
+
36
+ print(f"Loading JSON files from directory: {directory}")
37
+
38
+ json_files = [os.path.join(directory, f) for f in os.listdir(directory)
39
+ if f.endswith('.json') and os.path.isfile(os.path.join(directory, f))]
40
+
41
+ if not json_files:
42
+ raise ValueError(f"No JSON files found in directory {directory}")
43
+
44
+ print(f"Found {len(json_files)} JSON files")
45
+
46
+ all_data = []
47
+ for file_path in json_files:
48
+ try:
49
+ with open(file_path, 'r', encoding='utf-8') as f:
50
+ data_dict = json.load(f)
51
+ if 'data' in data_dict:
52
+ all_data.extend(data_dict['data'])
53
+ else:
54
+ print(f"Warning: 'data' key not found in {os.path.basename(file_path)}")
55
+ except Exception as e:
56
+ print(f"Error loading {os.path.basename(file_path)}: {str(e)}")
57
+
58
+ if not all_data:
59
+ raise ValueError("Failed to load data from JSON files")
60
+
61
+ df = pd.DataFrame(all_data)
62
+
63
+ label_mapping = {
64
+ 'ai': 'AI',
65
+ 'human': 'Human',
66
+ 'ai+rew': 'AI',
67
+ }
68
+
69
+ if 'source' in df.columns:
70
+ df['label'] = df['source'].map(lambda x: label_mapping.get(x, x))
71
+ else:
72
+ print("Warning: 'source' column not found, using default label")
73
+ df['label'] = 'Unknown'
74
+
75
+ valid_labels = ['AI', 'Human']
76
+ df = df[df['label'].isin(valid_labels)]
77
+
78
+ print(f"Filtered to {len(df)} examples with labels: {valid_labels}")
79
+ print(f"Label distribution: {df['label'].value_counts().to_dict()}")
80
+
81
+ return df
82
+
83
+ class Medium_Binary_Network(nn.Module):
84
+ def __init__(self, input_size, hidden_sizes=[256, 128, 64, 32], dropout=0.3):
85
+ super(Medium_Binary_Network, self).__init__()
86
+
87
+ layers = []
88
+ prev_size = input_size
89
+
90
+ for hidden_size in hidden_sizes:
91
+ layers.append(nn.Linear(prev_size, hidden_size))
92
+ layers.append(nn.ReLU())
93
+ layers.append(nn.Dropout(dropout))
94
+ prev_size = hidden_size
95
+
96
+ layers.append(nn.Linear(prev_size, 2))
97
+
98
+ self.model = nn.Sequential(*layers)
99
+
100
+ def forward(self, x):
101
+ return self.model(x)
102
+
103
+ def cross_validate_simple_classifier(directory_path="experiments/results/two_scores_with_long_text_analyze_2048T",
104
+ feature_config=None,
105
+ n_splits=5,
106
+ random_state=42,
107
+ epochs=100,
108
+ hidden_sizes=[256, 128, 64, 32],
109
+ dropout=0.3,
110
+ early_stopping_patience=10):
111
+ print("\n" + "="*50)
112
+ print("MEDIUM BINARY CLASSIFIER CROSS-VALIDATION")
113
+ print("="*50)
114
+
115
+ if feature_config is None:
116
+ feature_config = {
117
+ 'basic_scores': True,
118
+ 'basic_text_stats': ['total_tokens', 'total_words', 'unique_words', 'stop_words', 'avg_word_length'],
119
+ 'morphological': ['pos_distribution', 'unique_lemmas', 'lemma_word_ratio'],
120
+ 'syntactic': ['dependencies', 'noun_chunks'],
121
+ 'entities': ['total_entities', 'entity_types'],
122
+ 'diversity': ['ttr', 'mtld'],
123
+ 'structure': ['sentence_count', 'avg_sentence_length', 'question_sentences', 'exclamation_sentences'],
124
+ 'readability': ['words_per_sentence', 'syllables_per_word', 'flesh_kincaid_score', 'long_words_percent'],
125
+ 'semantic': True
126
+ }
127
+
128
+ df = load_data_from_json(directory_path)
129
+
130
+ features_df = select_features(df, feature_config)
131
+ print(f"Selected {len(features_df.columns)} features")
132
+
133
+ imputer = SimpleImputer(strategy='mean')
134
+ X = imputer.fit_transform(features_df)
135
+
136
+ label_encoder = LabelEncoder()
137
+ y = label_encoder.fit_transform(df['label'].values)
138
+
139
+ skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=random_state)
140
+
141
+ fold_metrics = []
142
+ fold_models = []
143
+
144
+ all_train_losses = []
145
+ all_val_losses = []
146
+ all_train_accs = []
147
+ all_val_accs = []
148
+
149
+ all_y_true = []
150
+ all_y_pred = []
151
+
152
+ best_fold_score = -1
153
+ best_fold_index = -1
154
+
155
+ for fold, (train_idx, test_idx) in enumerate(skf.split(X, y)):
156
+ print(f"\n{'='*20} Fold {fold+1}/{n_splits} {'='*20}")
157
+
158
+ X_train, X_test = X[train_idx], X[test_idx]
159
+ y_train, y_test = y[train_idx], y[test_idx]
160
+
161
+ scaler = StandardScaler()
162
+ X_train_scaled = scaler.fit_transform(X_train)
163
+ X_test_scaled = scaler.transform(X_test)
164
+
165
+ X_train_tensor = torch.FloatTensor(X_train_scaled).to(DEVICE)
166
+ y_train_tensor = torch.LongTensor(y_train).to(DEVICE)
167
+ X_test_tensor = torch.FloatTensor(X_test_scaled).to(DEVICE)
168
+ y_test_tensor = torch.LongTensor(y_test).to(DEVICE)
169
+
170
+ train_dataset = TensorDataset(X_train_tensor, y_train_tensor)
171
+ train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
172
+
173
+ model = Medium_Binary_Network(X_train_scaled.shape[1], hidden_sizes=hidden_sizes, dropout=dropout).to(DEVICE)
174
+ print(f"Model created with {len(hidden_sizes)} hidden layers: {hidden_sizes}")
175
+
176
+ criterion = nn.CrossEntropyLoss()
177
+ optimizer = optim.Adam(model.parameters(), lr=0.001, weight_decay=1e-5)
178
+ scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.5, patience=5, verbose=True)
179
+
180
+ best_val_loss = float('inf')
181
+ patience_counter = 0
182
+ best_model_state = None
183
+
184
+ train_losses = []
185
+ val_losses = []
186
+ train_accs = []
187
+ val_accs = []
188
+
189
+ for epoch in range(epochs):
190
+ model.train()
191
+ running_loss = 0.0
192
+ running_corrects = 0
193
+
194
+ for inputs, labels in train_loader:
195
+ optimizer.zero_grad()
196
+ outputs = model(inputs)
197
+ loss = criterion(outputs, labels)
198
+ loss.backward()
199
+ optimizer.step()
200
+
201
+ _, preds = torch.max(outputs, 1)
202
+ running_loss += loss.item() * inputs.size(0)
203
+ running_corrects += torch.sum(preds == labels).item()
204
+
205
+ epoch_loss = running_loss / len(train_loader.dataset)
206
+ epoch_acc = running_corrects / len(train_loader.dataset)
207
+ train_losses.append(epoch_loss)
208
+ train_accs.append(epoch_acc)
209
+
210
+ model.eval()
211
+ with torch.no_grad():
212
+ val_outputs = model(X_test_tensor)
213
+ val_loss = criterion(val_outputs, y_test_tensor)
214
+ val_losses.append(val_loss.item())
215
+
216
+ _, val_preds = torch.max(val_outputs, 1)
217
+ val_acc = torch.sum(val_preds == y_test_tensor).item() / len(y_test_tensor)
218
+ val_accs.append(val_acc)
219
+
220
+ if val_loss < best_val_loss:
221
+ best_val_loss = val_loss
222
+ patience_counter = 0
223
+ best_model_state = model.state_dict().copy()
224
+ else:
225
+ patience_counter += 1
226
+
227
+ if patience_counter >= early_stopping_patience:
228
+ print(f"Early stopping at epoch {epoch+1}")
229
+ break
230
+
231
+ scheduler.step(val_loss)
232
+
233
+ if (epoch + 1) % 10 == 0 or epoch == 0:
234
+ print(f"Epoch {epoch+1}/{epochs}, Train Loss: {epoch_loss:.4f}, Train Acc: {epoch_acc:.4f}, Val Loss: {val_loss:.4f}, Val Acc: {val_acc:.4f}")
235
+
236
+ if best_model_state:
237
+ model.load_state_dict(best_model_state)
238
+ print("Loaded best model weights")
239
+
240
+ model.eval()
241
+ with torch.no_grad():
242
+ test_outputs = model(X_test_tensor)
243
+ _, predicted = torch.max(test_outputs, 1)
244
+ test_acc = torch.sum(predicted == y_test_tensor).item() / len(y_test_tensor)
245
+
246
+ y_test_np = y_test
247
+ predicted_np = predicted.cpu().numpy()
248
+
249
+ all_y_true.extend(y_test_np)
250
+ all_y_pred.extend(predicted_np)
251
+
252
+ precision, recall, f1, _ = precision_recall_fscore_support(y_test_np, predicted_np, average='weighted')
253
+
254
+ fold_metric = {
255
+ 'fold': fold + 1,
256
+ 'accuracy': float(test_acc),
257
+ 'precision': float(precision),
258
+ 'recall': float(recall),
259
+ 'f1': float(f1),
260
+ 'val_loss': float(best_val_loss)
261
+ }
262
+
263
+ fold_metrics.append(fold_metric)
264
+
265
+ fold_models.append({
266
+ 'model': model,
267
+ 'scaler': scaler,
268
+ 'label_encoder': label_encoder,
269
+ 'imputer': imputer,
270
+ 'score': test_acc
271
+ })
272
+
273
+ if test_acc > best_fold_score:
274
+ best_fold_score = test_acc
275
+ best_fold_index = fold
276
+
277
+ all_train_losses.extend(train_losses)
278
+ all_val_losses.extend(val_losses)
279
+ all_train_accs.extend(train_accs)
280
+ all_val_accs.extend(val_accs)
281
+
282
+ print(f"Fold {fold+1} Results:")
283
+ print(f" Accuracy: {test_acc:.4f}")
284
+ print(f" Precision: {precision:.4f}")
285
+ print(f" Recall: {recall:.4f}")
286
+ print(f" F1 Score: {f1:.4f}")
287
+
288
+ overall_accuracy = accuracy_score(all_y_true, all_y_pred)
289
+ overall_precision, overall_recall, overall_f1, _ = precision_recall_fscore_support(
290
+ all_y_true, all_y_pred, average='weighted'
291
+ )
292
+
293
+ fold_accuracies = [metrics['accuracy'] for metrics in fold_metrics]
294
+ mean_accuracy = np.mean(fold_accuracies)
295
+ std_accuracy = np.std(fold_accuracies)
296
+
297
+ ci_lower = mean_accuracy - 1.96 * std_accuracy / np.sqrt(n_splits)
298
+ ci_upper = mean_accuracy + 1.96 * std_accuracy / np.sqrt(n_splits)
299
+
300
+ plot_learning_curve(all_train_losses, all_val_losses)
301
+ plot_accuracy_curve(all_train_accs, all_val_accs)
302
+
303
+ class_names = label_encoder.classes_
304
+ cm = confusion_matrix(all_y_true, all_y_pred)
305
+ plt.figure(figsize=(10, 8))
306
+ sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
307
+ xticklabels=class_names,
308
+ yticklabels=class_names)
309
+ plt.title('Binary Classification Confusion Matrix (Cross-Validation)')
310
+ plt.ylabel('True Label')
311
+ plt.xlabel('Predicted Label')
312
+ os.makedirs('plots/binary', exist_ok=True)
313
+ plt.savefig('plots/binary/confusion_matrix_medium.png')
314
+ plt.close()
315
+
316
+ print("\n" + "="*50)
317
+ print("CROSS-VALIDATION SUMMARY")
318
+ print("="*50)
319
+ print(f"Mean Accuracy: {mean_accuracy:.4f} ± {std_accuracy:.4f}")
320
+ print(f"95% Confidence Interval: [{ci_lower:.4f}, {ci_upper:.4f}]")
321
+ print(f"Overall Accuracy: {overall_accuracy:.4f}")
322
+ print(f"Overall Precision: {overall_precision:.4f}")
323
+ print(f"Overall Recall: {overall_recall:.4f}")
324
+ print(f"Overall F1: {overall_f1:.4f}")
325
+
326
+ print(f"\nBest Fold: {best_fold_index + 1} (Accuracy: {fold_metrics[best_fold_index]['accuracy']:.4f})")
327
+
328
+ best_model_data = fold_models[best_fold_index]
329
+
330
+ results = {
331
+ 'fold_metrics': fold_metrics,
332
+ 'overall': {
333
+ 'accuracy': float(overall_accuracy),
334
+ 'precision': float(overall_precision),
335
+ 'recall': float(overall_recall),
336
+ 'f1': float(overall_f1)
337
+ },
338
+ 'cross_validation': {
339
+ 'mean_accuracy': float(mean_accuracy),
340
+ 'std_accuracy': float(std_accuracy),
341
+ 'confidence_interval_95': [float(ci_lower), float(ci_upper)]
342
+ },
343
+ 'best_fold': {
344
+ 'fold': best_fold_index + 1,
345
+ 'accuracy': float(fold_metrics[best_fold_index]['accuracy'])
346
+ },
347
+ 'model_config': {
348
+ 'hidden_sizes': hidden_sizes,
349
+ 'dropout': dropout
350
+ }
351
+ }
352
+
353
+ output_dir = 'models/medium_binary_classifier'
354
+ save_paths = save_binary_model(best_model_data, results, output_dir=output_dir)
355
+
356
+ return best_model_data, results, save_paths
357
+
358
+ def plot_learning_curve(train_losses, val_losses):
359
+ plt.figure(figsize=(10, 6))
360
+ epochs = range(1, len(train_losses) + 1)
361
+
362
+ plt.plot(epochs, train_losses, 'b-', label='Training Loss')
363
+ plt.plot(epochs, val_losses, 'r-', label='Validation Loss')
364
+
365
+ plt.title('Learning Curve')
366
+ plt.xlabel('Epochs')
367
+ plt.ylabel('Loss')
368
+ plt.legend()
369
+ plt.grid(True)
370
+
371
+ os.makedirs('plots/binary', exist_ok=True)
372
+ plt.savefig('plots/binary/learning_curve.png')
373
+ plt.close()
374
+ print("Learning curve saved to plots/binary/learning_curve.png")
375
+
376
+ def plot_accuracy_curve(train_accuracies, val_accuracies):
377
+ plt.figure(figsize=(10, 6))
378
+ epochs = range(1, len(train_accuracies) + 1)
379
+
380
+ plt.plot(epochs, train_accuracies, 'g-', label='Training Accuracy')
381
+ plt.plot(epochs, val_accuracies, 'm-', label='Validation Accuracy')
382
+
383
+ plt.title('Accuracy Curve')
384
+ plt.xlabel('Epochs')
385
+ plt.ylabel('Accuracy')
386
+ plt.legend()
387
+ plt.grid(True)
388
+
389
+ plt.ylim(0, 1.0)
390
+
391
+ os.makedirs('plots/binary', exist_ok=True)
392
+ plt.savefig('plots/binary/accuracy_curve.png')
393
+ plt.close()
394
+ print("Accuracy curve saved to plots/binary/accuracy_curve.png")
395
+
396
+ def select_features(df, feature_config):
397
+ features_df = pd.DataFrame()
398
+
399
+ if feature_config.get('basic_scores', True):
400
+ if 'score_chat' in df.columns:
401
+ features_df['score_chat'] = df['score_chat']
402
+ if 'score_coder' in df.columns:
403
+ features_df['score_coder'] = df['score_coder']
404
+
405
+ if 'text_analysis' in df.columns:
406
+ if feature_config.get('basic_text_stats'):
407
+ for feature in feature_config['basic_text_stats']:
408
+ features_df[f'basic_{feature}'] = df['text_analysis'].apply(
409
+ lambda x: x.get('basic_stats', {}).get(feature, 0) if isinstance(x, dict) else 0
410
+ )
411
+
412
+ if feature_config.get('morphological'):
413
+ for feature in feature_config['morphological']:
414
+ if feature == 'pos_distribution':
415
+ pos_types = ['NOUN', 'VERB', 'ADJ', 'ADV', 'PROPN', 'DET', 'ADP', 'PRON', 'CCONJ', 'SCONJ']
416
+ for pos in pos_types:
417
+ features_df[f'pos_{pos}'] = df['text_analysis'].apply(
418
+ lambda x: x.get('morphological_analysis', {}).get('pos_distribution', {}).get(pos, 0)
419
+ if isinstance(x, dict) else 0
420
+ )
421
+ else:
422
+ features_df[f'morph_{feature}'] = df['text_analysis'].apply(
423
+ lambda x: x.get('morphological_analysis', {}).get(feature, 0) if isinstance(x, dict) else 0
424
+ )
425
+
426
+ if feature_config.get('syntactic'):
427
+ for feature in feature_config['syntactic']:
428
+ if feature == 'dependencies':
429
+ dep_types = ['nsubj', 'obj', 'amod', 'nmod', 'ROOT', 'punct', 'case']
430
+ for dep in dep_types:
431
+ features_df[f'dep_{dep}'] = df['text_analysis'].apply(
432
+ lambda x: x.get('syntactic_analysis', {}).get('dependencies', {}).get(dep, 0)
433
+ if isinstance(x, dict) else 0
434
+ )
435
+ else:
436
+ features_df[f'synt_{feature}'] = df['text_analysis'].apply(
437
+ lambda x: x.get('syntactic_analysis', {}).get(feature, 0) if isinstance(x, dict) else 0
438
+ )
439
+
440
+ if feature_config.get('entities'):
441
+ for feature in feature_config['entities']:
442
+ if feature == 'entity_types':
443
+ entity_types = ['PER', 'LOC', 'ORG']
444
+ for ent in entity_types:
445
+ features_df[f'ent_{ent}'] = df['text_analysis'].apply(
446
+ lambda x: x.get('named_entities', {}).get('entity_types', {}).get(ent, 0)
447
+ if isinstance(x, dict) else 0
448
+ )
449
+ else:
450
+ features_df[f'ent_{feature}'] = df['text_analysis'].apply(
451
+ lambda x: x.get('named_entities', {}).get(feature, 0) if isinstance(x, dict) else 0
452
+ )
453
+
454
+ if feature_config.get('diversity'):
455
+ for feature in feature_config['diversity']:
456
+ features_df[f'div_{feature}'] = df['text_analysis'].apply(
457
+ lambda x: x.get('lexical_diversity', {}).get(feature, 0) if isinstance(x, dict) else 0
458
+ )
459
+
460
+ if feature_config.get('structure'):
461
+ for feature in feature_config['structure']:
462
+ features_df[f'struct_{feature}'] = df['text_analysis'].apply(
463
+ lambda x: x.get('text_structure', {}).get(feature, 0) if isinstance(x, dict) else 0
464
+ )
465
+
466
+ if feature_config.get('readability'):
467
+ for feature in feature_config['readability']:
468
+ features_df[f'read_{feature}'] = df['text_analysis'].apply(
469
+ lambda x: x.get('readability', {}).get(feature, 0) if isinstance(x, dict) else 0
470
+ )
471
+
472
+ if feature_config.get('semantic'):
473
+ features_df['semantic_coherence'] = df['text_analysis'].apply(
474
+ lambda x: x.get('semantic_coherence', {}).get('avg_coherence_score', 0) if isinstance(x, dict) else 0
475
+ )
476
+
477
+ print(f"Generated {len(features_df.columns)} features")
478
+ return features_df
479
+
480
+ def augment_text_features(features_df, num_augmentations=5, noise_factor=0.05):
481
+ augmented_dfs = [features_df]
482
+
483
+ for i in range(num_augmentations):
484
+ numeric_cols = features_df.select_dtypes(include=[np.number]).columns
485
+ augmented_df = features_df.copy()
486
+ for col in numeric_cols:
487
+ augmented_df[col] = augmented_df[col].astype(float)
488
+
489
+ noise = augmented_df[numeric_cols] * np.random.normal(0, noise_factor, size=augmented_df[numeric_cols].shape)
490
+ augmented_df[numeric_cols] += noise
491
+ augmented_dfs.append(augmented_df)
492
+
493
+ return pd.concat(augmented_dfs, ignore_index=True)
494
+
495
+ def cross_validate_binary_classifier(directory_path="experiments/results/two_scores_with_long_text_analyze_2048T",
496
+ model_config=None,
497
+ feature_config=None,
498
+ n_splits=5,
499
+ random_state=42,
500
+ epochs=100,
501
+ early_stopping_patience=10,
502
+ use_augmentation=True,
503
+ num_augmentations=2,
504
+ noise_factor=0.05):
505
+ if model_config is None:
506
+ model_config = {
507
+ 'hidden_layers': [256, 128, 64],
508
+ 'dropout_rate': 0.3
509
+ }
510
+
511
+ if feature_config is None:
512
+ feature_config = {
513
+ 'basic_scores': True,
514
+ 'basic_text_stats': ['total_tokens', 'total_words', 'unique_words', 'stop_words', 'avg_word_length'],
515
+ 'morphological': ['pos_distribution', 'unique_lemmas', 'lemma_word_ratio'],
516
+ 'syntactic': ['dependencies', 'noun_chunks'],
517
+ 'entities': ['total_entities', 'entity_types'],
518
+ 'diversity': ['ttr', 'mtld'],
519
+ 'structure': ['sentence_count', 'avg_sentence_length', 'question_sentences', 'exclamation_sentences'],
520
+ 'readability': ['words_per_sentence', 'syllables_per_word', 'flesh_kincaid_score', 'long_words_percent'],
521
+ 'semantic': True
522
+ }
523
+
524
+ print("\n" + "="*50)
525
+ print("BINARY CLASSIFIER CROSS-VALIDATION")
526
+ print("="*50)
527
+
528
+ df = load_data_from_json(directory_path)
529
+
530
+ features_df = select_features(df, feature_config)
531
+ print(f"Selected features: {features_df.columns.tolist()}")
532
+
533
+ imputer = SimpleImputer(strategy='mean')
534
+
535
+ if use_augmentation:
536
+ print(f"Augmenting data with {num_augmentations} copies (noise factor: {noise_factor})...")
537
+ original_size = len(features_df)
538
+ features_df_augmented = augment_text_features(features_df,
539
+ num_augmentations=num_augmentations,
540
+ noise_factor=noise_factor)
541
+ y_augmented = np.tile(df['label'].values, num_augmentations + 1)
542
+ print(f"Data size increased from {original_size} to {len(features_df_augmented)}")
543
+
544
+ X = imputer.fit_transform(features_df_augmented)
545
+ y = y_augmented
546
+ else:
547
+ X = imputer.fit_transform(features_df)
548
+ y = df['label'].values
549
+
550
+ label_encoder = LabelEncoder()
551
+ y_encoded = label_encoder.fit_transform(y)
552
+
553
+ print(f"Data size: {X.shape}")
554
+ print(f"Labels distribution: {pd.Series(y).value_counts().to_dict()}")
555
+
556
+ skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=random_state)
557
+
558
+ fold_metrics = []
559
+ fold_models = []
560
+ all_y_true = []
561
+ all_y_pred = []
562
+ all_y_scores = []
563
+
564
+ best_fold_score = -1
565
+ best_fold_index = -1
566
+
567
+ print(f"\nPerforming {n_splits}-fold cross-validation...")
568
+
569
+ num_avg_epochs = 5
570
+ saved_weights = []
571
+
572
+ for fold, (train_idx, test_idx) in enumerate(skf.split(X, y_encoded)):
573
+ print(f"\n{'='*20} Fold {fold+1}/{n_splits} {'='*20}")
574
+
575
+ X_train, X_test = X[train_idx], X[test_idx]
576
+ y_train, y_test = y_encoded[train_idx], y_encoded[test_idx]
577
+
578
+ scaler = StandardScaler()
579
+ X_train_scaled = scaler.fit_transform(X_train)
580
+ X_test_scaled = scaler.transform(X_test)
581
+
582
+ X_train_tensor = torch.FloatTensor(X_train_scaled).to(DEVICE)
583
+ y_train_tensor = torch.LongTensor(y_train).to(DEVICE)
584
+ X_test_tensor = torch.FloatTensor(X_test_scaled).to(DEVICE)
585
+ y_test_tensor = torch.LongTensor(y_test).to(DEVICE)
586
+
587
+ train_dataset = TensorDataset(X_train_tensor, y_train_tensor)
588
+ train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
589
+
590
+ num_classes = len(label_encoder.classes_)
591
+ model = build_neural_network(X_train_scaled.shape[1], num_classes,
592
+ hidden_layers=model_config['hidden_layers'])
593
+
594
+ criterion = nn.CrossEntropyLoss()
595
+ optimizer = optim.Adam(model.parameters(), lr=0.001, weight_decay=1e-5)
596
+ scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.95)
597
+
598
+ best_val_loss = float('inf')
599
+ patience_counter = 0
600
+ best_model_state = None
601
+
602
+ train_losses = []
603
+ val_losses = []
604
+
605
+ saved_weights = []
606
+
607
+ for epoch in range(epochs):
608
+ model.train()
609
+ running_loss = 0.0
610
+
611
+ for inputs, labels in train_loader:
612
+ optimizer.zero_grad()
613
+ outputs = model(inputs)
614
+ loss = criterion(outputs, labels)
615
+ loss.backward()
616
+ optimizer.step()
617
+
618
+ running_loss += loss.item() * inputs.size(0)
619
+
620
+ epoch_loss = running_loss / len(train_loader.dataset)
621
+ train_losses.append(epoch_loss)
622
+
623
+ model.eval()
624
+ with torch.no_grad():
625
+ val_outputs = model(X_test_tensor)
626
+ val_loss = criterion(val_outputs, y_test_tensor)
627
+ val_losses.append(val_loss.item())
628
+
629
+ if val_loss < best_val_loss:
630
+ best_val_loss = val_loss
631
+ patience_counter = 0
632
+ best_model_state = model.state_dict().copy()
633
+ else:
634
+ patience_counter += 1
635
+
636
+ if patience_counter >= early_stopping_patience:
637
+ print(f"Early stopping at epoch {epoch+1}")
638
+ break
639
+
640
+ if epoch >= epochs - num_avg_epochs:
641
+ saved_weights.append(model.state_dict().copy())
642
+
643
+ scheduler.step()
644
+
645
+ if (epoch + 1) % 10 == 0 or epoch == 0:
646
+ print(f"Epoch {epoch+1}/{epochs}, Train Loss: {epoch_loss:.4f}, Val Loss: {val_loss:.4f}")
647
+
648
+ if len(saved_weights) > 0:
649
+ print(f"Averaging weights from last {len(saved_weights)} epochs...")
650
+ avg_state_dict = saved_weights[0].copy()
651
+ for key in avg_state_dict.keys():
652
+ if epoch >= epochs - num_avg_epochs:
653
+ for i in range(1, len(saved_weights)):
654
+ avg_state_dict[key] += saved_weights[i][key]
655
+ avg_state_dict[key] /= len(saved_weights)
656
+
657
+ model.load_state_dict(avg_state_dict)
658
+ print("Model loaded with averaged weights")
659
+ elif best_model_state:
660
+ model.load_state_dict(best_model_state)
661
+ print("Model loaded with best validation weights")
662
+
663
+ model.eval()
664
+ with torch.no_grad():
665
+ test_outputs = model(X_test_tensor)
666
+ _, predicted = torch.max(test_outputs.data, 1)
667
+ predicted_np = predicted.cpu().numpy()
668
+
669
+ probabilities = torch.softmax(test_outputs, dim=1)
670
+ pos_scores = probabilities[:, 1].cpu().numpy()
671
+
672
+ all_y_true.extend(y_test)
673
+ all_y_pred.extend(predicted_np)
674
+ all_y_scores.extend(pos_scores)
675
+
676
+ fold_acc = accuracy_score(y_test, predicted_np)
677
+ precision, recall, f1, _ = precision_recall_fscore_support(y_test, predicted_np, average='weighted')
678
+
679
+ try:
680
+ fold_auc = roc_auc_score(y_test, pos_scores)
681
+ except:
682
+ fold_auc = 0.0
683
+ print("Warning: Could not compute AUC")
684
+
685
+ fold_metrics.append({
686
+ 'fold': fold + 1,
687
+ 'accuracy': float(fold_acc),
688
+ 'precision': float(precision),
689
+ 'recall': float(recall),
690
+ 'f1': float(f1),
691
+ 'auc': float(fold_auc),
692
+ 'best_val_loss': float(best_val_loss)
693
+ })
694
+
695
+ fold_models.append({
696
+ 'model': model,
697
+ 'scaler': scaler,
698
+ 'label_encoder': label_encoder,
699
+ 'imputer': imputer,
700
+ 'score': fold_acc
701
+ })
702
+
703
+ if fold_acc > best_fold_score:
704
+ best_fold_score = fold_acc
705
+ best_fold_index = fold
706
+
707
+ print(f"Fold {fold+1} Results:")
708
+ print(f" Accuracy: {fold_acc:.4f}")
709
+ print(f" Precision: {precision:.4f}")
710
+ print(f" Recall: {recall:.4f}")
711
+ print(f" F1 Score: {f1:.4f}")
712
+ if fold_auc > 0:
713
+ print(f" AUC: {fold_auc:.4f}")
714
+
715
+ overall_accuracy = accuracy_score(all_y_true, all_y_pred)
716
+ overall_precision, overall_recall, overall_f1, _ = precision_recall_fscore_support(
717
+ all_y_true, all_y_pred, average='weighted'
718
+ )
719
+
720
+ try:
721
+ overall_auc = roc_auc_score(all_y_true, all_y_scores)
722
+ except:
723
+ overall_auc = 0.0
724
+ print("Warning: Could not compute overall AUC")
725
+
726
+ fold_accuracies = [metrics['accuracy'] for metrics in fold_metrics]
727
+ mean_accuracy = np.mean(fold_accuracies)
728
+ std_accuracy = np.std(fold_accuracies)
729
+
730
+ ci_lower = mean_accuracy - 1.96 * std_accuracy / np.sqrt(n_splits)
731
+ ci_upper = mean_accuracy + 1.96 * std_accuracy / np.sqrt(n_splits)
732
+
733
+ class_counts = np.bincount(y_encoded)
734
+ baseline_accuracy = np.max(class_counts) / len(y_encoded)
735
+ most_frequent_class = np.argmax(class_counts)
736
+
737
+ t_stat, p_value = stats.ttest_1samp(fold_accuracies, baseline_accuracy)
738
+
739
+ best_model_data = fold_models[best_fold_index]
740
+
741
+ class_names = label_encoder.classes_
742
+ cm = confusion_matrix(all_y_true, all_y_pred)
743
+ plt.figure(figsize=(10, 8))
744
+ sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
745
+ xticklabels=class_names,
746
+ yticklabels=class_names)
747
+ plt.title('Binary Classification Confusion Matrix (Cross-Validation)')
748
+ plt.ylabel('True Label')
749
+ plt.xlabel('Predicted Label')
750
+ os.makedirs('plots/binary', exist_ok=True)
751
+ plt.savefig('plots/binary/confusion_matrix_cv.png')
752
+ plt.close()
753
+
754
+ if overall_auc > 0:
755
+ from sklearn.metrics import roc_curve
756
+ fpr, tpr, _ = roc_curve(all_y_true, all_y_scores)
757
+ plt.figure(figsize=(10, 8))
758
+ plt.plot(fpr, tpr, lw=2, label=f'ROC curve (AUC = {overall_auc:.4f})')
759
+ plt.plot([0, 1], [0, 1], 'k--', lw=2)
760
+ plt.xlim([0.0, 1.0])
761
+ plt.ylim([0.0, 1.05])
762
+ plt.xlabel('False Positive Rate')
763
+ plt.ylabel('True Positive Rate')
764
+ plt.title('Receiver Operating Characteristic (ROC)')
765
+ plt.legend(loc="lower right")
766
+ plt.savefig('plots/binary/roc_curve.png')
767
+ plt.close()
768
+
769
+ results = {
770
+ 'fold_metrics': fold_metrics,
771
+ 'overall': {
772
+ 'accuracy': float(overall_accuracy),
773
+ 'precision': float(overall_precision),
774
+ 'recall': float(overall_recall),
775
+ 'f1': float(overall_f1),
776
+ 'auc': float(overall_auc) if overall_auc > 0 else None
777
+ },
778
+ 'cross_validation': {
779
+ 'mean_accuracy': float(mean_accuracy),
780
+ 'std_accuracy': float(std_accuracy),
781
+ 'confidence_interval_95': [float(ci_lower), float(ci_upper)],
782
+ 'baseline_accuracy': float(baseline_accuracy),
783
+ 'most_frequent_class': str(label_encoder.inverse_transform([most_frequent_class])[0]),
784
+ 't_statistic': float(t_stat),
785
+ 'p_value': float(p_value),
786
+ 'statistically_significant': "yes" if p_value < 0.05 else "no"
787
+ },
788
+ 'best_fold': {
789
+ 'fold': best_fold_index + 1,
790
+ 'accuracy': float(fold_metrics[best_fold_index]['accuracy'])
791
+ }
792
+ }
793
+
794
+ print("\n" + "="*50)
795
+ print("CROSS-VALIDATION SUMMARY")
796
+ print("="*50)
797
+ print(f"Mean Accuracy: {mean_accuracy:.4f} ± {std_accuracy:.4f}")
798
+ print(f"95% Confidence Interval: [{ci_lower:.4f}, {ci_upper:.4f}]")
799
+ print(f"Overall Accuracy: {overall_accuracy:.4f}")
800
+ print(f"Baseline Accuracy: {baseline_accuracy:.4f} (most frequent class: {label_encoder.inverse_transform([most_frequent_class])[0]})")
801
+ print(f"T-statistic: {t_stat:.4f}, p-value: {p_value:.6f}")
802
+
803
+ if p_value < 0.05:
804
+ print("The model is significantly better than the baseline (p < 0.05)")
805
+ else:
806
+ print("The model is NOT significantly better than the baseline (p >= 0.05)")
807
+
808
+ print(f"\nBest Fold: {best_fold_index + 1} (Accuracy: {fold_metrics[best_fold_index]['accuracy']:.4f})")
809
+
810
+ return best_model_data, results
811
+
812
+ def save_binary_model(model_data, results, output_dir='models/binary_classifier'):
813
+ if not os.path.exists(output_dir):
814
+ os.makedirs(output_dir)
815
+
816
+ model_path = os.path.join(output_dir, 'nn_model.pt')
817
+ torch.save(model_data['model'].state_dict(), model_path)
818
+
819
+ scaler_path = os.path.join(output_dir, 'scaler.joblib')
820
+ joblib.dump(model_data['scaler'], scaler_path)
821
+
822
+ encoder_path = os.path.join(output_dir, 'label_encoder.joblib')
823
+ joblib.dump(model_data['label_encoder'], encoder_path)
824
+
825
+ imputer_path = os.path.join(output_dir, 'imputer.joblib')
826
+ joblib.dump(model_data['imputer'], imputer_path)
827
+
828
+ results_path = os.path.join(output_dir, 'cv_results.json')
829
+ with open(results_path, 'w') as f:
830
+ json.dump(results, f, indent=4)
831
+
832
+ print(f"Binary model saved to {model_path}")
833
+ print(f"CV results saved to {results_path}")
834
+
835
+ return {
836
+ 'model_path': model_path,
837
+ 'scaler_path': scaler_path,
838
+ 'encoder_path': encoder_path,
839
+ 'imputer_path': imputer_path,
840
+ 'results_path': results_path
841
+ }
842
+
843
+ def parse_args():
844
+ parser = argparse.ArgumentParser(description='Binary Neural Network Classifier (Human vs AI) with Cross-Validation')
845
+ parser.add_argument('--random_seed', type=int, default=42,
846
+ help='Random seed for reproducibility')
847
+ parser.add_argument('--folds', type=int, default=5,
848
+ help='Number of cross-validation folds')
849
+ parser.add_argument('--epochs', type=int, default=100,
850
+ help='Maximum number of training epochs per fold')
851
+ parser.add_argument('--patience', type=int, default=10,
852
+ help='Early stopping patience (epochs)')
853
+ return parser.parse_args()
854
+
855
+ def main():
856
+ print("\n" + "="*50)
857
+ print("MEDIUM BINARY CLASSIFIER")
858
+ print("="*50 + "\n")
859
+
860
+ args = parse_args()
861
+
862
+ seed = args.random_seed
863
+ np.random.seed(seed)
864
+ torch.manual_seed(seed)
865
+ if GPU_AVAILABLE:
866
+ torch.cuda.manual_seed_all(seed)
867
+
868
+ plt.switch_backend('agg')
869
+
870
+ feature_config = {
871
+ 'basic_scores': True,
872
+ 'basic_text_stats': ['total_tokens', 'total_words', 'unique_words', 'stop_words', 'avg_word_length'],
873
+ 'morphological': ['pos_distribution', 'unique_lemmas', 'lemma_word_ratio'],
874
+ 'syntactic': ['dependencies', 'noun_chunks'],
875
+ 'entities': ['total_entities', 'entity_types'],
876
+ 'diversity': ['ttr', 'mtld'],
877
+ 'structure': ['sentence_count', 'avg_sentence_length', 'question_sentences', 'exclamation_sentences'],
878
+ 'readability': ['words_per_sentence', 'syllables_per_word', 'flesh_kincaid_score', 'long_words_percent'],
879
+ 'semantic': True
880
+ }
881
+
882
+ model_data, results, save_paths = cross_validate_simple_classifier(
883
+ directory_path="experiments/results/two_scores_with_long_text_analyze_2048T",
884
+ feature_config=feature_config,
885
+ n_splits=5,
886
+ random_state=seed,
887
+ epochs=150,
888
+ hidden_sizes=[256, 192, 128, 64],
889
+ dropout=0.3,
890
+ early_stopping_patience=15
891
+ )
892
+
893
+ print("\nTraining completed.")
894
+ print(f"Medium binary classifier saved to {save_paths['model_path']}")
895
+
896
+ if __name__ == "__main__":
897
+ main()