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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 train_test_split
|
8 |
+
from sklearn.metrics import classification_report, accuracy_score
|
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 sklearn.model_selection import StratifiedKFold
|
17 |
+
from scipy import stats
|
18 |
+
import time
|
19 |
+
import argparse
|
20 |
+
|
21 |
+
def setup_gpu():
|
22 |
+
if torch.cuda.is_available():
|
23 |
+
return True
|
24 |
+
else:
|
25 |
+
print("No GPUs found. Using CPU.")
|
26 |
+
return False
|
27 |
+
|
28 |
+
GPU_AVAILABLE = setup_gpu()
|
29 |
+
DEVICE = torch.device('cuda' if GPU_AVAILABLE else 'cpu')
|
30 |
+
|
31 |
+
def load_data_from_json(directory_path):
|
32 |
+
if os.path.isfile(directory_path):
|
33 |
+
directory = os.path.dirname(directory_path)
|
34 |
+
else:
|
35 |
+
directory = directory_path
|
36 |
+
|
37 |
+
print(f"Loading JSON files from directory: {directory}")
|
38 |
+
|
39 |
+
json_files = [os.path.join(directory, f) for f in os.listdir(directory)
|
40 |
+
if f.endswith('.json') and os.path.isfile(os.path.join(directory, f))]
|
41 |
+
|
42 |
+
if not json_files:
|
43 |
+
raise ValueError(f"No JSON files found in directory {directory}")
|
44 |
+
|
45 |
+
print(f"Found {len(json_files)} JSON files")
|
46 |
+
|
47 |
+
all_data = []
|
48 |
+
for file_path in json_files:
|
49 |
+
try:
|
50 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
51 |
+
data_dict = json.load(f)
|
52 |
+
if 'data' in data_dict:
|
53 |
+
all_data.extend(data_dict['data'])
|
54 |
+
else:
|
55 |
+
print(f"Warning: 'data' key not found in {os.path.basename(file_path)}")
|
56 |
+
except Exception as e:
|
57 |
+
print(f"Error loading {os.path.basename(file_path)}: {str(e)}")
|
58 |
+
|
59 |
+
if not all_data:
|
60 |
+
raise ValueError("Failed to load data from JSON files")
|
61 |
+
|
62 |
+
df = pd.DataFrame(all_data)
|
63 |
+
|
64 |
+
label_mapping = {
|
65 |
+
'ai': 'Raw AI',
|
66 |
+
'human': 'Human',
|
67 |
+
'ai+rew': 'Rephrased AI'
|
68 |
+
}
|
69 |
+
|
70 |
+
if 'source' in df.columns:
|
71 |
+
df['label'] = df['source'].map(lambda x: label_mapping.get(x, x))
|
72 |
+
else:
|
73 |
+
print("Warning: 'source' column not found, using default label")
|
74 |
+
df['label'] = 'Unknown'
|
75 |
+
|
76 |
+
return df
|
77 |
+
|
78 |
+
class Neural_Network(nn.Module):
|
79 |
+
def __init__(self, input_size, hidden_layers, num_classes, dropout_rate=0.2):
|
80 |
+
super(Neural_Network, self).__init__()
|
81 |
+
|
82 |
+
layers = []
|
83 |
+
prev_size = input_size
|
84 |
+
|
85 |
+
for hidden_size in hidden_layers:
|
86 |
+
layers.append(nn.Linear(prev_size, hidden_size))
|
87 |
+
layers.append(nn.ReLU())
|
88 |
+
layers.append(nn.Dropout(dropout_rate))
|
89 |
+
prev_size = hidden_size
|
90 |
+
|
91 |
+
layers.append(nn.Linear(prev_size, num_classes))
|
92 |
+
self.model = nn.Sequential(*layers)
|
93 |
+
|
94 |
+
def forward(self, x):
|
95 |
+
return self.model(x)
|
96 |
+
|
97 |
+
def build_neural_network(input_shape, num_classes, hidden_layers=[64, 32]):
|
98 |
+
model = Neural_Network(input_shape, hidden_layers, num_classes).to(DEVICE)
|
99 |
+
print(f"Model created with hidden layers {hidden_layers} on device: {DEVICE}")
|
100 |
+
return model
|
101 |
+
|
102 |
+
def plot_learning_curve(train_losses, val_losses):
|
103 |
+
plt.figure(figsize=(10, 6))
|
104 |
+
epochs = range(1, len(train_losses) + 1)
|
105 |
+
|
106 |
+
plt.plot(epochs, train_losses, 'b-', label='Training Loss')
|
107 |
+
plt.plot(epochs, val_losses, 'r-', label='Validation Loss')
|
108 |
+
|
109 |
+
plt.title('Learning Curve')
|
110 |
+
plt.xlabel('Epochs')
|
111 |
+
plt.ylabel('Loss')
|
112 |
+
plt.legend()
|
113 |
+
plt.grid(True)
|
114 |
+
|
115 |
+
os.makedirs('plots', exist_ok=True)
|
116 |
+
plt.savefig('plots/learning_curve.png')
|
117 |
+
plt.close()
|
118 |
+
print("Learning curve saved to plots/learning_curve.png")
|
119 |
+
|
120 |
+
def plot_accuracy_curve(train_accuracies, val_accuracies):
|
121 |
+
plt.figure(figsize=(10, 6))
|
122 |
+
epochs = range(1, len(train_accuracies) + 1)
|
123 |
+
|
124 |
+
plt.plot(epochs, train_accuracies, 'g-', label='Training Accuracy')
|
125 |
+
plt.plot(epochs, val_accuracies, 'm-', label='Validation Accuracy')
|
126 |
+
|
127 |
+
plt.title('Accuracy Curve')
|
128 |
+
plt.xlabel('Epochs')
|
129 |
+
plt.ylabel('Accuracy')
|
130 |
+
plt.legend()
|
131 |
+
plt.grid(True)
|
132 |
+
|
133 |
+
plt.ylim(0, 1.0)
|
134 |
+
|
135 |
+
os.makedirs('plots', exist_ok=True)
|
136 |
+
plt.savefig('plots/accuracy_curve.png')
|
137 |
+
plt.close()
|
138 |
+
print("Accuracy curve saved to plots/accuracy_curve.png")
|
139 |
+
|
140 |
+
def select_features(df, feature_config):
|
141 |
+
features_df = pd.DataFrame()
|
142 |
+
|
143 |
+
if feature_config.get('basic_scores', True):
|
144 |
+
if 'score_chat' in df.columns:
|
145 |
+
features_df['score_chat'] = df['score_chat']
|
146 |
+
if 'score_coder' in df.columns:
|
147 |
+
features_df['score_coder'] = df['score_coder']
|
148 |
+
|
149 |
+
if 'text_analysis' in df.columns:
|
150 |
+
if feature_config.get('basic_text_stats'):
|
151 |
+
for feature in feature_config['basic_text_stats']:
|
152 |
+
features_df[f'basic_{feature}'] = df['text_analysis'].apply(
|
153 |
+
lambda x: x.get('basic_stats', {}).get(feature, 0) if isinstance(x, dict) else 0
|
154 |
+
)
|
155 |
+
|
156 |
+
if feature_config.get('morphological'):
|
157 |
+
for feature in feature_config['morphological']:
|
158 |
+
if feature == 'pos_distribution':
|
159 |
+
pos_types = ['NOUN', 'VERB', 'ADJ', 'ADV', 'PROPN', 'DET', 'ADP', 'PRON', 'CCONJ', 'SCONJ']
|
160 |
+
for pos in pos_types:
|
161 |
+
features_df[f'pos_{pos}'] = df['text_analysis'].apply(
|
162 |
+
lambda x: x.get('morphological_analysis', {}).get('pos_distribution', {}).get(pos, 0)
|
163 |
+
if isinstance(x, dict) else 0
|
164 |
+
)
|
165 |
+
else:
|
166 |
+
features_df[f'morph_{feature}'] = df['text_analysis'].apply(
|
167 |
+
lambda x: x.get('morphological_analysis', {}).get(feature, 0) if isinstance(x, dict) else 0
|
168 |
+
)
|
169 |
+
|
170 |
+
if feature_config.get('syntactic'):
|
171 |
+
for feature in feature_config['syntactic']:
|
172 |
+
if feature == 'dependencies':
|
173 |
+
dep_types = ['nsubj', 'obj', 'amod', 'nmod', 'ROOT', 'punct', 'case']
|
174 |
+
for dep in dep_types:
|
175 |
+
features_df[f'dep_{dep}'] = df['text_analysis'].apply(
|
176 |
+
lambda x: x.get('syntactic_analysis', {}).get('dependencies', {}).get(dep, 0)
|
177 |
+
if isinstance(x, dict) else 0
|
178 |
+
)
|
179 |
+
else:
|
180 |
+
features_df[f'synt_{feature}'] = df['text_analysis'].apply(
|
181 |
+
lambda x: x.get('syntactic_analysis', {}).get(feature, 0) if isinstance(x, dict) else 0
|
182 |
+
)
|
183 |
+
|
184 |
+
if feature_config.get('entities'):
|
185 |
+
for feature in feature_config['entities']:
|
186 |
+
if feature == 'entity_types':
|
187 |
+
entity_types = ['PER', 'LOC', 'ORG']
|
188 |
+
for ent in entity_types:
|
189 |
+
features_df[f'ent_{ent}'] = df['text_analysis'].apply(
|
190 |
+
lambda x: x.get('named_entities', {}).get('entity_types', {}).get(ent, 0)
|
191 |
+
if isinstance(x, dict) else 0
|
192 |
+
)
|
193 |
+
else:
|
194 |
+
features_df[f'ent_{feature}'] = df['text_analysis'].apply(
|
195 |
+
lambda x: x.get('named_entities', {}).get(feature, 0) if isinstance(x, dict) else 0
|
196 |
+
)
|
197 |
+
|
198 |
+
if feature_config.get('diversity'):
|
199 |
+
for feature in feature_config['diversity']:
|
200 |
+
features_df[f'div_{feature}'] = df['text_analysis'].apply(
|
201 |
+
lambda x: x.get('lexical_diversity', {}).get(feature, 0) if isinstance(x, dict) else 0
|
202 |
+
)
|
203 |
+
|
204 |
+
if feature_config.get('structure'):
|
205 |
+
for feature in feature_config['structure']:
|
206 |
+
features_df[f'struct_{feature}'] = df['text_analysis'].apply(
|
207 |
+
lambda x: x.get('text_structure', {}).get(feature, 0) if isinstance(x, dict) else 0
|
208 |
+
)
|
209 |
+
|
210 |
+
if feature_config.get('readability'):
|
211 |
+
for feature in feature_config['readability']:
|
212 |
+
features_df[f'read_{feature}'] = df['text_analysis'].apply(
|
213 |
+
lambda x: x.get('readability', {}).get(feature, 0) if isinstance(x, dict) else 0
|
214 |
+
)
|
215 |
+
|
216 |
+
if feature_config.get('semantic'):
|
217 |
+
features_df['semantic_coherence'] = df['text_analysis'].apply(
|
218 |
+
lambda x: x.get('semantic_coherence', {}).get('avg_coherence_score', 0) if isinstance(x, dict) else 0
|
219 |
+
)
|
220 |
+
|
221 |
+
print(f"Generated {len(features_df.columns)} features")
|
222 |
+
return features_df
|
223 |
+
|
224 |
+
def train_neural_network(directory_path="experiments/results/two_scores_with_long_text_analyze_2048T",
|
225 |
+
model_config=None,
|
226 |
+
feature_config=None,
|
227 |
+
random_state=42):
|
228 |
+
if model_config is None:
|
229 |
+
model_config = {
|
230 |
+
'hidden_layers': [128, 96, 64, 32],
|
231 |
+
'dropout_rate': 0.1
|
232 |
+
}
|
233 |
+
|
234 |
+
if feature_config is None:
|
235 |
+
feature_config = {
|
236 |
+
'basic_scores': True,
|
237 |
+
'basic_text_stats': ['total_tokens', 'total_words', 'unique_words', 'stop_words', 'avg_word_length'],
|
238 |
+
'morphological': ['pos_distribution', 'unique_lemmas', 'lemma_word_ratio'],
|
239 |
+
'syntactic': ['dependencies', 'noun_chunks'],
|
240 |
+
'entities': ['total_entities', 'entity_types'],
|
241 |
+
'diversity': ['ttr', 'mtld'],
|
242 |
+
'structure': ['sentence_count', 'avg_sentence_length', 'question_sentences', 'exclamation_sentences'],
|
243 |
+
'readability': ['words_per_sentence', 'syllables_per_word', 'flesh_kincaid_score', 'long_words_percent'],
|
244 |
+
'semantic': True
|
245 |
+
}
|
246 |
+
|
247 |
+
df = load_data_from_json(directory_path)
|
248 |
+
|
249 |
+
features_df = select_features(df, feature_config)
|
250 |
+
|
251 |
+
print(f"Selected features: {features_df.columns.tolist()}")
|
252 |
+
|
253 |
+
imputer = SimpleImputer(strategy='mean')
|
254 |
+
X = imputer.fit_transform(features_df)
|
255 |
+
y = df['label'].values
|
256 |
+
|
257 |
+
print(f"Final data size after NaN processing: {X.shape}")
|
258 |
+
print(f"Labels distribution: {pd.Series(y).value_counts().to_dict()}")
|
259 |
+
|
260 |
+
label_encoder = LabelEncoder()
|
261 |
+
y_encoded = label_encoder.fit_transform(y)
|
262 |
+
|
263 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
264 |
+
X, y_encoded, test_size=0.2, random_state=random_state
|
265 |
+
)
|
266 |
+
|
267 |
+
X_train, X_val, y_train, y_val = train_test_split(
|
268 |
+
X_train, y_train, test_size=0.2, random_state=random_state
|
269 |
+
)
|
270 |
+
|
271 |
+
scaler = StandardScaler()
|
272 |
+
X_train_scaled = scaler.fit_transform(X_train)
|
273 |
+
X_val_scaled = scaler.transform(X_val)
|
274 |
+
X_test_scaled = scaler.transform(X_test)
|
275 |
+
|
276 |
+
X_train_tensor = torch.FloatTensor(X_train_scaled).to(DEVICE)
|
277 |
+
y_train_tensor = torch.LongTensor(y_train).to(DEVICE)
|
278 |
+
X_val_tensor = torch.FloatTensor(X_val_scaled).to(DEVICE)
|
279 |
+
y_val_tensor = torch.LongTensor(y_val).to(DEVICE)
|
280 |
+
X_test_tensor = torch.FloatTensor(X_test_scaled).to(DEVICE)
|
281 |
+
|
282 |
+
train_dataset = TensorDataset(X_train_tensor, y_train_tensor)
|
283 |
+
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
|
284 |
+
|
285 |
+
num_classes = len(label_encoder.classes_)
|
286 |
+
model = build_neural_network(X_train_scaled.shape[1], num_classes,
|
287 |
+
hidden_layers=model_config['hidden_layers'])
|
288 |
+
|
289 |
+
criterion = nn.CrossEntropyLoss()
|
290 |
+
optimizer = optim.Adam(model.parameters(), lr=0.001)
|
291 |
+
|
292 |
+
num_epochs = 100
|
293 |
+
best_loss = float('inf')
|
294 |
+
patience = 10
|
295 |
+
patience_counter = 0
|
296 |
+
best_model_state = None
|
297 |
+
|
298 |
+
train_losses = []
|
299 |
+
val_losses = []
|
300 |
+
train_accuracies = []
|
301 |
+
val_accuracies = []
|
302 |
+
|
303 |
+
for epoch in range(num_epochs):
|
304 |
+
model.train()
|
305 |
+
running_loss = 0.0
|
306 |
+
correct_train = 0
|
307 |
+
total_train = 0
|
308 |
+
|
309 |
+
for inputs, labels in train_loader:
|
310 |
+
optimizer.zero_grad()
|
311 |
+
outputs = model(inputs)
|
312 |
+
loss = criterion(outputs, labels)
|
313 |
+
loss.backward()
|
314 |
+
optimizer.step()
|
315 |
+
|
316 |
+
running_loss += loss.item() * inputs.size(0)
|
317 |
+
|
318 |
+
_, predicted = torch.max(outputs.data, 1)
|
319 |
+
total_train += labels.size(0)
|
320 |
+
correct_train += (predicted == labels).sum().item()
|
321 |
+
|
322 |
+
epoch_loss = running_loss / len(train_loader.dataset)
|
323 |
+
train_losses.append(epoch_loss)
|
324 |
+
|
325 |
+
train_accuracy = correct_train / total_train
|
326 |
+
train_accuracies.append(train_accuracy)
|
327 |
+
|
328 |
+
model.eval()
|
329 |
+
with torch.no_grad():
|
330 |
+
val_outputs = model(X_val_tensor)
|
331 |
+
val_loss = criterion(val_outputs, y_val_tensor)
|
332 |
+
val_losses.append(val_loss.item())
|
333 |
+
|
334 |
+
_, predicted_val = torch.max(val_outputs.data, 1)
|
335 |
+
val_accuracy = (predicted_val == y_val_tensor).sum().item() / len(y_val_tensor)
|
336 |
+
val_accuracies.append(val_accuracy)
|
337 |
+
|
338 |
+
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss:.4f}, Acc: {train_accuracy:.4f}, Val Loss: {val_loss:.4f}, Val Acc: {val_accuracy:.4f}")
|
339 |
+
|
340 |
+
if val_loss < best_loss:
|
341 |
+
best_loss = val_loss
|
342 |
+
patience_counter = 0
|
343 |
+
best_model_state = model.state_dict().copy()
|
344 |
+
else:
|
345 |
+
patience_counter += 1
|
346 |
+
|
347 |
+
if patience_counter >= patience:
|
348 |
+
print(f"Early stopping at epoch {epoch+1}")
|
349 |
+
break
|
350 |
+
|
351 |
+
plot_learning_curve(train_losses, val_losses)
|
352 |
+
plot_accuracy_curve(train_accuracies, val_accuracies)
|
353 |
+
|
354 |
+
if best_model_state:
|
355 |
+
model.load_state_dict(best_model_state)
|
356 |
+
|
357 |
+
model.eval()
|
358 |
+
with torch.no_grad():
|
359 |
+
y_pred_prob = model(X_test_tensor)
|
360 |
+
y_pred = torch.argmax(y_pred_prob, dim=1).cpu().numpy()
|
361 |
+
|
362 |
+
accuracy = accuracy_score(y_test, y_pred)
|
363 |
+
print(f"Model accuracy: {accuracy:.6f}")
|
364 |
+
|
365 |
+
class_names = label_encoder.classes_
|
366 |
+
print("\nClassification report:")
|
367 |
+
print(classification_report(y_test, y_pred, target_names=class_names))
|
368 |
+
|
369 |
+
return model, scaler, label_encoder, accuracy
|
370 |
+
|
371 |
+
def save_model(model, scaler, label_encoder, imputer, output_dir='models/neural_network'):
|
372 |
+
if not os.path.exists(output_dir):
|
373 |
+
os.makedirs(output_dir)
|
374 |
+
|
375 |
+
model_path = os.path.join(output_dir, 'nn_model.pt')
|
376 |
+
torch.save(model.state_dict(), model_path)
|
377 |
+
|
378 |
+
scaler_path = os.path.join(output_dir, 'scaler.joblib')
|
379 |
+
joblib.dump(scaler, scaler_path)
|
380 |
+
|
381 |
+
encoder_path = os.path.join(output_dir, 'label_encoder.joblib')
|
382 |
+
joblib.dump(label_encoder, encoder_path)
|
383 |
+
|
384 |
+
imputer_path = os.path.join(output_dir, 'imputer.joblib')
|
385 |
+
joblib.dump(imputer, imputer_path)
|
386 |
+
|
387 |
+
print(f"Model saved to {model_path}")
|
388 |
+
print(f"Scaler saved to {scaler_path}")
|
389 |
+
print(f"Label encoder saved to {encoder_path}")
|
390 |
+
print(f"Imputer saved to {imputer_path}")
|
391 |
+
|
392 |
+
return model_path, scaler_path, encoder_path, imputer_path
|
393 |
+
|
394 |
+
def evaluate_statistical_significance(X, y, model_config, scaler, label_encoder, cv=5, random_state=42, cv_epochs=15):
|
395 |
+
print("Starting statistical significance evaluation...")
|
396 |
+
|
397 |
+
skf = StratifiedKFold(n_splits=cv, shuffle=True, random_state=random_state)
|
398 |
+
cv_scores = []
|
399 |
+
all_y_true = []
|
400 |
+
all_y_pred = []
|
401 |
+
|
402 |
+
class_counts = np.bincount(y)
|
403 |
+
baseline_accuracy = np.max(class_counts) / len(y)
|
404 |
+
most_frequent_class = np.argmax(class_counts)
|
405 |
+
|
406 |
+
print(f"Baseline (most frequent class) accuracy: {baseline_accuracy:.4f}")
|
407 |
+
print(f"Most frequent class: {label_encoder.inverse_transform([most_frequent_class])[0]}")
|
408 |
+
|
409 |
+
fold = 1
|
410 |
+
for train_idx, test_idx in skf.split(X, y):
|
411 |
+
print(f"\nTraining fold {fold}/{cv}...")
|
412 |
+
|
413 |
+
X_train_fold, X_test_fold = X[train_idx], X[test_idx]
|
414 |
+
y_train_fold, y_test_fold = y[train_idx], y[test_idx]
|
415 |
+
|
416 |
+
X_train_scaled = scaler.transform(X_train_fold)
|
417 |
+
X_test_scaled = scaler.transform(X_test_fold)
|
418 |
+
|
419 |
+
X_train_tensor = torch.FloatTensor(X_train_scaled).to(DEVICE)
|
420 |
+
y_train_tensor = torch.LongTensor(y_train_fold).to(DEVICE)
|
421 |
+
X_test_tensor = torch.FloatTensor(X_test_scaled).to(DEVICE)
|
422 |
+
|
423 |
+
input_size = X_train_scaled.shape[1]
|
424 |
+
num_classes = len(np.unique(y))
|
425 |
+
model = build_neural_network(input_size, num_classes, hidden_layers=model_config['hidden_layers'])
|
426 |
+
|
427 |
+
criterion = nn.CrossEntropyLoss()
|
428 |
+
optimizer = optim.Adam(model.parameters(), lr=0.001)
|
429 |
+
|
430 |
+
train_dataset = TensorDataset(X_train_tensor, y_train_tensor)
|
431 |
+
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
|
432 |
+
|
433 |
+
model.train()
|
434 |
+
for epoch in range(cv_epochs):
|
435 |
+
for inputs, labels in train_loader:
|
436 |
+
optimizer.zero_grad()
|
437 |
+
outputs = model(inputs)
|
438 |
+
loss = criterion(outputs, labels)
|
439 |
+
loss.backward()
|
440 |
+
optimizer.step()
|
441 |
+
|
442 |
+
model.eval()
|
443 |
+
with torch.no_grad():
|
444 |
+
outputs = model(X_test_tensor)
|
445 |
+
_, predicted = torch.max(outputs.data, 1)
|
446 |
+
predicted_np = predicted.cpu().numpy()
|
447 |
+
|
448 |
+
fold_accuracy = (predicted_np == y_test_fold).mean()
|
449 |
+
cv_scores.append(fold_accuracy)
|
450 |
+
|
451 |
+
all_y_true.extend(y_test_fold)
|
452 |
+
all_y_pred.extend(predicted_np)
|
453 |
+
|
454 |
+
print(f"Fold {fold} accuracy: {fold_accuracy:.4f}")
|
455 |
+
|
456 |
+
fold += 1
|
457 |
+
|
458 |
+
cv_scores = np.array(cv_scores)
|
459 |
+
mean_accuracy = cv_scores.mean()
|
460 |
+
std_accuracy = cv_scores.std()
|
461 |
+
|
462 |
+
ci_lower = mean_accuracy - 1.96 * std_accuracy / np.sqrt(cv)
|
463 |
+
ci_upper = mean_accuracy + 1.96 * std_accuracy / np.sqrt(cv)
|
464 |
+
|
465 |
+
t_stat, p_value = stats.ttest_1samp(cv_scores, baseline_accuracy)
|
466 |
+
|
467 |
+
results = {
|
468 |
+
'cv_scores': [float(score) for score in cv_scores.tolist()],
|
469 |
+
'mean_accuracy': float(mean_accuracy),
|
470 |
+
'std_accuracy': float(std_accuracy),
|
471 |
+
'confidence_interval_95': [float(ci_lower), float(ci_upper)],
|
472 |
+
'baseline_accuracy': float(baseline_accuracy),
|
473 |
+
't_statistic': float(t_stat),
|
474 |
+
'p_value': float(p_value),
|
475 |
+
'statistically_significant': "yes" if p_value < 0.05 else "no"
|
476 |
+
}
|
477 |
+
|
478 |
+
print("\nStatistical Significance Results:")
|
479 |
+
print(f"Cross-validation accuracy: {mean_accuracy:.4f} ± {std_accuracy:.4f}")
|
480 |
+
print(f"95% confidence interval: [{ci_lower:.4f}, {ci_upper:.4f}]")
|
481 |
+
print(f"Baseline accuracy (most frequent class): {baseline_accuracy:.4f}")
|
482 |
+
print(f"t-statistic: {t_stat:.4f}, p-value: {p_value:.6f}")
|
483 |
+
|
484 |
+
if p_value < 0.05:
|
485 |
+
print("The model is significantly better than the baseline (p < 0.05)")
|
486 |
+
else:
|
487 |
+
print("The model is NOT significantly better than the baseline (p >= 0.05)")
|
488 |
+
|
489 |
+
class_names = label_encoder.classes_
|
490 |
+
cm = pd.crosstab(
|
491 |
+
pd.Series(all_y_true, name='Actual'),
|
492 |
+
pd.Series(all_y_pred, name='Predicted'),
|
493 |
+
normalize='index'
|
494 |
+
)
|
495 |
+
|
496 |
+
cm.index = [class_names[i] for i in range(len(class_names))]
|
497 |
+
cm.columns = [class_names[i] for i in range(len(class_names))]
|
498 |
+
|
499 |
+
plt.figure(figsize=(10, 8))
|
500 |
+
sns.heatmap(cm, annot=True, fmt='.2f', cmap='Blues')
|
501 |
+
plt.title('Normalized Confusion Matrix (Cross-Validation)')
|
502 |
+
plt.ylabel('True Label')
|
503 |
+
plt.xlabel('Predicted Label')
|
504 |
+
|
505 |
+
os.makedirs('plots', exist_ok=True)
|
506 |
+
plt.savefig('plots/confusion_matrix_cv.png')
|
507 |
+
plt.close()
|
508 |
+
print("Confusion matrix saved to plots/confusion_matrix_cv.png")
|
509 |
+
|
510 |
+
return results
|
511 |
+
|
512 |
+
def parse_args():
|
513 |
+
parser = argparse.ArgumentParser(description='Neural Network Classifier with Statistical Significance Testing')
|
514 |
+
parser.add_argument('--random_seed', type=int, default=None,
|
515 |
+
help='Random seed for reproducibility. If not provided, a random seed will be generated.')
|
516 |
+
parser.add_argument('--multiple_runs', type=int, default=1,
|
517 |
+
help='Number of runs with different random seeds')
|
518 |
+
return parser.parse_args()
|
519 |
+
|
520 |
+
def main():
|
521 |
+
args = parse_args()
|
522 |
+
|
523 |
+
if args.random_seed is None:
|
524 |
+
seed = int(time.time() * 1000) % 10000
|
525 |
+
print(f"Using random seed: {seed}")
|
526 |
+
else:
|
527 |
+
seed = args.random_seed
|
528 |
+
print(f"Using provided seed: {seed}")
|
529 |
+
|
530 |
+
all_run_results = []
|
531 |
+
|
532 |
+
for run in range(args.multiple_runs):
|
533 |
+
if args.multiple_runs > 1:
|
534 |
+
current_seed = seed + run
|
535 |
+
print(f"\n\nRun {run+1}/{args.multiple_runs} with seed {current_seed}\n")
|
536 |
+
else:
|
537 |
+
current_seed = seed
|
538 |
+
|
539 |
+
np.random.seed(current_seed)
|
540 |
+
torch.manual_seed(current_seed)
|
541 |
+
if GPU_AVAILABLE:
|
542 |
+
torch.cuda.manual_seed_all(current_seed)
|
543 |
+
torch.backends.cudnn.deterministic = True
|
544 |
+
torch.backends.cudnn.benchmark = False
|
545 |
+
|
546 |
+
plt.switch_backend('agg')
|
547 |
+
|
548 |
+
model_config = {
|
549 |
+
'hidden_layers': [128, 96, 64, 32],
|
550 |
+
'dropout_rate': 0.1
|
551 |
+
}
|
552 |
+
|
553 |
+
feature_config = {
|
554 |
+
'basic_scores': True,
|
555 |
+
'basic_text_stats': ['total_tokens', 'total_words', 'unique_words', 'stop_words', 'avg_word_length'],
|
556 |
+
'morphological': ['pos_distribution', 'unique_lemmas', 'lemma_word_ratio'],
|
557 |
+
'syntactic': ['dependencies', 'noun_chunks'],
|
558 |
+
'entities': ['total_entities', 'entity_types'],
|
559 |
+
'diversity': ['ttr', 'mtld'],
|
560 |
+
'structure': ['sentence_count', 'avg_sentence_length', 'question_sentences', 'exclamation_sentences'],
|
561 |
+
'readability': ['words_per_sentence', 'syllables_per_word', 'flesh_kincaid_score', 'long_words_percent'],
|
562 |
+
'semantic': True
|
563 |
+
}
|
564 |
+
|
565 |
+
model, scaler, label_encoder, accuracy = train_neural_network(
|
566 |
+
directory_path="experiments/results/two_scores_with_long_text_analyze_2048T",
|
567 |
+
model_config=model_config,
|
568 |
+
feature_config=feature_config,
|
569 |
+
random_state=current_seed
|
570 |
+
)
|
571 |
+
|
572 |
+
print("\nPerforming statistical significance testing...")
|
573 |
+
df = load_data_from_json("experiments/results/two_scores_with_long_text_analyze_2048T")
|
574 |
+
features_df = select_features(df, feature_config)
|
575 |
+
|
576 |
+
imputer = SimpleImputer(strategy='mean')
|
577 |
+
X = imputer.fit_transform(features_df)
|
578 |
+
y = df['label'].values
|
579 |
+
y_encoded = label_encoder.transform(y)
|
580 |
+
|
581 |
+
significance_results = evaluate_statistical_significance(
|
582 |
+
X, y_encoded, model_config, scaler, label_encoder, cv=5, random_state=current_seed
|
583 |
+
)
|
584 |
+
|
585 |
+
run_info = {
|
586 |
+
'run_id': run + 1,
|
587 |
+
'seed': current_seed,
|
588 |
+
'accuracy': float(accuracy),
|
589 |
+
'statistical_significance': significance_results
|
590 |
+
}
|
591 |
+
all_run_results.append(run_info)
|
592 |
+
|
593 |
+
output_dir = f'models/neural_network/run_{run+1}_seed_{current_seed}'
|
594 |
+
os.makedirs(output_dir, exist_ok=True)
|
595 |
+
|
596 |
+
with open(f'{output_dir}/statistical_results.json', 'w') as f:
|
597 |
+
json.dump(significance_results, f, indent=4)
|
598 |
+
|
599 |
+
save_model(model, scaler, label_encoder, imputer, output_dir='models/neural_network')
|
600 |
+
|
601 |
+
if args.multiple_runs > 1:
|
602 |
+
accuracy_values = [run['accuracy'] for run in all_run_results]
|
603 |
+
mean_accuracy = np.mean(accuracy_values)
|
604 |
+
std_accuracy = np.std(accuracy_values)
|
605 |
+
|
606 |
+
print("\n" + "="*60)
|
607 |
+
print(f"SUMMARY OF {args.multiple_runs} RUNS")
|
608 |
+
print("="*60)
|
609 |
+
print(f"Mean accuracy: {mean_accuracy:.4f} ± {std_accuracy:.4f}")
|
610 |
+
print(f"Min accuracy: {min(accuracy_values):.4f}, Max accuracy: {max(accuracy_values):.4f}")
|
611 |
+
|
612 |
+
summary = {
|
613 |
+
'num_runs': args.multiple_runs,
|
614 |
+
'base_seed': seed,
|
615 |
+
'accuracy_mean': float(mean_accuracy),
|
616 |
+
'accuracy_std': float(std_accuracy),
|
617 |
+
'accuracy_min': float(min(accuracy_values)),
|
618 |
+
'accuracy_max': float(max(accuracy_values)),
|
619 |
+
'all_runs': all_run_results
|
620 |
+
}
|
621 |
+
|
622 |
+
with open('models/neural_network/multiple_runs_summary.json', 'w') as f:
|
623 |
+
json.dump(summary, f, indent=4)
|
624 |
+
print("Summary saved to models/neural_network/multiple_runs_summary.json")
|
625 |
+
|
626 |
+
if __name__ == "__main__":
|
627 |
+
main()
|
models/neural_network/imputer.joblib
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:188d4008a04267264ab8575a77248bc14c9918ead0e586b549fb4844cb306039
|
3 |
+
size 1975
|
models/neural_network/label_encoder.joblib
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d4df61318f184976384ce86efad867496f329e47f12723440beadd5e5649a7f3
|
3 |
+
size 563
|
models/neural_network/nn_model.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1aeb4b7a9081b2efcd63fc50f07325d00fd20aa3ab776e0398b7bf8263ae9f95
|
3 |
+
size 109126
|
models/neural_network/scaler.joblib
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:827e410b2b95d876fde7a040998dd3a2415a1fec96962c284a93473aeaba192b
|
3 |
+
size 1623
|