-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStep8.2-FindOptimalParametersForLLM.py
More file actions
1787 lines (1480 loc) · 78.7 KB
/
Step8.2-FindOptimalParametersForLLM.py
File metadata and controls
1787 lines (1480 loc) · 78.7 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
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
from typing import Dict, List, Tuple, Union, Optional, Any
import re
import warnings
from tqdm.auto import tqdm
from dataclasses import dataclass, field, asdict
import logging
from scipy import stats
import matplotlib.ticker as mtick
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('qa_analysis')
# Filter specific warnings
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
os.environ['GENSIM_DATA_DIR'] = '/data/ascher02/uqmmune1/BioStarsGPT/temp/'
os.environ['TRANSFORMERS_CACHE'] = '/data/ascher02/uqmmune1/BioStarsGPT/temp/huggingface'
os.environ['SENTENCE_TRANSFORMERS_HOME'] = '/data/ascher02/uqmmune1/BioStarsGPT/temp/sentence_transformers'
# Initialize NLTK resources
import nltk
try:
nltk.data.find('tokenizers/punkt')
nltk.data.find('corpora/stopwords')
except LookupError:
logger.info("Downloading NLTK resources...")
nltk.download('punkt', quiet=True)
nltk.download('stopwords', quiet=True)
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
# Try to import advanced libraries with fallbacks
try:
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
PLOTLY_AVAILABLE = True
logger.info("Plotly is available for interactive visualizations")
except ImportError:
PLOTLY_AVAILABLE = False
logger.info("Plotly not found, will use Matplotlib for visualizations")
try:
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
SENTENCE_TRANSFORMERS_AVAILABLE = True
logger.info("Sentence Transformers is available for semantic analysis")
except ImportError:
SENTENCE_TRANSFORMERS_AVAILABLE = False
logger.info("Sentence Transformers not found, will use simpler methods for analysis")
try:
import spacy
try:
nlp = spacy.load('en_core_web_sm')
logger.info("Loaded spaCy model")
SPACY_AVAILABLE = True
except:
logger.info("Downloading spaCy model...")
spacy.cli.download('en_core_web_sm')
nlp = spacy.load('en_core_web_sm')
SPACY_AVAILABLE = True
except ImportError:
logger.warning("SpaCy not available, falling back to basic NLTK")
SPACY_AVAILABLE = False
# Fixed BERTopic import with OpenAI compatibility check
try:
# First check for proper OpenAI compatibility to avoid AttributeError
try:
import openai
# Check if the new client structure is available
if hasattr(openai, 'OpenAI'):
# BERTopic should work with this version of OpenAI
from bertopic import BERTopic
BERTOPIC_AVAILABLE = True
logger.info("BERTopic is available for advanced topic modeling")
else:
# OpenAI version is incompatible with BERTopic
logger.warning("OpenAI version incompatible with BERTopic (needs openai>=1.0.0)")
BERTOPIC_AVAILABLE = False
except ImportError:
# No OpenAI, try importing BERTopic directly
from bertopic import BERTopic
BERTOPIC_AVAILABLE = True
logger.info("BERTopic is available for advanced topic modeling")
except (ImportError, AttributeError) as e:
BERTOPIC_AVAILABLE = False
logger.info(f"BERTopic not available: {str(e)}. Will use LDA for topic modeling")
# Import sklearn components
try:
from sklearn.decomposition import LatentDirichletAllocation, NMF, TruncatedSVD
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.model_selection import KFold
from sklearn.metrics import silhouette_score, coherence_score
except ImportError:
# Handle the possibility that coherence_score might not be available
from sklearn.decomposition import LatentDirichletAllocation, NMF, TruncatedSVD
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.model_selection import KFold
from sklearn.metrics import silhouette_score
try:
import umap
UMAP_AVAILABLE = True
logger.info("UMAP is available for dimensionality reduction")
except ImportError:
UMAP_AVAILABLE = False
logger.info("UMAP not found, will use TruncatedSVD for dimensionality reduction")
try:
from wordcloud import WordCloud
WORDCLOUD_AVAILABLE = True
except ImportError:
WORDCLOUD_AVAILABLE = False
logger.info("WordCloud not found, will skip wordcloud generation")
@dataclass
class DataStatistics:
"""Statistics about the dataset length and distribution."""
total_pairs: int = 0
avg_question_length: float = 0.0
avg_explanation_length: float = 0.0
max_question_length: int = 0
max_explanation_length: int = 0
min_question_length: int = 0
min_explanation_length: int = 0
median_question_length: float = 0.0
median_explanation_length: float = 0.0
percentile_90_question_length: float = 0.0
percentile_90_explanation_length: float = 0.0
total_question_tokens: int = 0
total_explanation_tokens: int = 0
def to_dict(self) -> Dict[str, Union[int, float]]:
return asdict(self)
@dataclass
class CodeStatistics:
"""Statistics about code presence in the dataset."""
questions_with_code: int = 0
explanations_with_code: int = 0
questions_with_code_percent: float = 0.0
explanations_with_code_percent: float = 0.0
def to_dict(self) -> Dict[str, Union[int, float]]:
return asdict(self)
@dataclass
class ComplexityMetrics:
"""Metrics for content complexity assessment."""
linguistic_complexity_score: float = 0.0
diversity_score: float = 0.0
perplexity: Optional[float] = None
coherence: Optional[float] = None
assessment: str = "Medium"
confidence_interval: Tuple[float, float] = (0.0, 0.0)
def to_dict(self) -> Dict[str, Union[float, str, Tuple[float, float]]]:
return asdict(self)
@dataclass
class HyperParameters:
"""Recommended hyperparameters for model training."""
model_name: str = "unsloth/Llama-3.3-8B-Instruct"
max_seq_length: int = 2048
load_in_4bit: bool = True
train_samples: int = 0
test_samples: int = 0
num_epochs: int = 3
learning_rate: float = 2e-5
batch_size: int = 1
gradient_accumulation_steps: int = 8
warmup_ratio: float = 0.03
lora_r: int = 16
lora_alpha: int = 32
lora_dropout: float = 0.05
target_modules: List[str] = field(default_factory=lambda: [
"q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"
])
eval_every_epochs: int = 1
generation_max_length: int = 512
generation_temperature: float = 0.7
generation_min_p: float = 0.1
generation_top_p: float = 0.92
seed: int = 42
weight_decay: float = 0.01
lr_scheduler_type: str = "cosine"
optimizer: str = "adamw_8bit"
dataset_complexity: str = "Medium"
diversity_score: float = 0.5
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
class QADataAnalyzer:
"""
A comprehensive analyzer for question-answer datasets that performs
advanced NLP analysis and recommends optimal fine-tuning parameters.
"""
def __init__(
self,
input_file: str,
output_dir: str = "analysis_output",
confidence_level: float = 0.95,
plot_format: str = "svg"
):
"""
Initialize the QA data analyzer.
Args:
input_file: Path to the JSONL file containing prompt-completion pairs
output_dir: Directory to save analysis outputs
confidence_level: Confidence level for statistical intervals (default: 0.95)
plot_format: File format for saving plots (default: svg)
"""
self.input_file = input_file
self.output_dir = output_dir
self.confidence_level = confidence_level
self.plot_format = plot_format
self.df = None
self.stop_words = set(stopwords.words('english'))
# Create output directory
os.makedirs(output_dir, exist_ok=True)
# Create subdirectories for organization
os.makedirs(os.path.join(output_dir, "plots"), exist_ok=True)
os.makedirs(os.path.join(output_dir, "data"), exist_ok=True)
# Initialize statistics containers
self.data_stats = DataStatistics()
self.code_stats = CodeStatistics()
self.complexity = ComplexityMetrics()
self.hyperparams = HyperParameters()
# Track additional metadata
self.keywords = []
self.entities = []
self.topics = {}
logger.info(f"Initialized analyzer for {input_file}")
logger.info(f"Output will be saved to {output_dir}")
def load_data(self) -> None:
"""Load and preprocess the dataset from JSONL."""
logger.info(f"Loading data from {self.input_file}...")
qa_pairs = []
try:
with open(self.input_file, 'r', encoding='utf-8') as f:
for line in f:
try:
item = json.loads(line)
if 'prompt' in item and 'completion' in item:
qa_pairs.append({
'question': item['prompt'],
'explanation': item['completion']
})
else:
logger.warning("Found JSONL entry without prompt/completion fields")
except json.JSONDecodeError:
logger.warning(f"Skipping invalid JSON line: {line[:50]}...")
except FileNotFoundError:
logger.error(f"Input file not found: {self.input_file}")
raise
if not qa_pairs:
logger.error("No valid prompt-completion pairs found in the input file")
raise ValueError("No valid prompt-completion pairs found")
self.df = pd.DataFrame(qa_pairs)
logger.info(f"Loaded {len(self.df)} prompt-completion pairs")
# Calculate token lengths using improved tokenization
if SPACY_AVAILABLE:
self.df['question_tokens'] = self.df['question'].apply(
lambda x: len([token for token in nlp(x)]))
self.df['explanation_tokens'] = self.df['explanation'].apply(
lambda x: len([token for token in nlp(x)]))
else:
self.df['question_tokens'] = self.df['question'].apply(
lambda x: len(word_tokenize(x)))
self.df['explanation_tokens'] = self.df['explanation'].apply(
lambda x: len(word_tokenize(x)))
# Handle outliers with statistical methods
q1_question = self.df['question_tokens'].quantile(0.25)
q3_question = self.df['question_tokens'].quantile(0.75)
iqr_question = q3_question - q1_question
q1_explanation = self.df['explanation_tokens'].quantile(0.25)
q3_explanation = self.df['explanation_tokens'].quantile(0.75)
iqr_explanation = q3_explanation - q1_explanation
# Flag outliers (for reporting, not filtering)
self.df['question_outlier'] = (
(self.df['question_tokens'] < (q1_question - 1.5 * iqr_question)) |
(self.df['question_tokens'] > (q3_question + 1.5 * iqr_question))
)
self.df['explanation_outlier'] = (
(self.df['explanation_tokens'] < (q1_explanation - 1.5 * iqr_explanation)) |
(self.df['explanation_tokens'] > (q3_explanation + 1.5 * iqr_explanation))
)
num_outliers = sum(self.df['question_outlier'] | self.df['explanation_outlier'])
logger.info(f"Identified {num_outliers} potential outliers ({num_outliers/len(self.df)*100:.1f}%)")
def compute_basic_statistics(self) -> None:
"""Calculate basic statistics about the dataset."""
q_lengths = self.df['question_tokens']
e_lengths = self.df['explanation_tokens']
# Compute basic statistics
self.data_stats.total_pairs = len(self.df)
self.data_stats.avg_question_length = float(q_lengths.mean())
self.data_stats.avg_explanation_length = float(e_lengths.mean())
self.data_stats.max_question_length = int(q_lengths.max())
self.data_stats.max_explanation_length = int(e_lengths.max())
self.data_stats.min_question_length = int(q_lengths.min())
self.data_stats.min_explanation_length = int(e_lengths.min())
self.data_stats.median_question_length = float(q_lengths.median())
self.data_stats.median_explanation_length = float(e_lengths.median())
self.data_stats.percentile_90_question_length = float(q_lengths.quantile(0.9))
self.data_stats.percentile_90_explanation_length = float(e_lengths.quantile(0.9))
self.data_stats.total_question_tokens = int(q_lengths.sum())
self.data_stats.total_explanation_tokens = int(e_lengths.sum())
# Calculate bootstrap confidence intervals for mean lengths
n_bootstrap = 1000
q_means = np.zeros(n_bootstrap)
e_means = np.zeros(n_bootstrap)
for i in range(n_bootstrap):
q_sample = np.random.choice(q_lengths, size=len(q_lengths), replace=True)
e_sample = np.random.choice(e_lengths, size=len(e_lengths), replace=True)
q_means[i] = np.mean(q_sample)
e_means[i] = np.mean(e_sample)
alpha = 1 - self.confidence_level
q_ci_lower = np.percentile(q_means, alpha/2 * 100)
q_ci_upper = np.percentile(q_means, (1-alpha/2) * 100)
e_ci_lower = np.percentile(e_means, alpha/2 * 100)
e_ci_upper = np.percentile(e_means, (1-alpha/2) * 100)
logger.info(f"Question length: {self.data_stats.avg_question_length:.1f} tokens "
f"({q_ci_lower:.1f} - {q_ci_upper:.1f}, {self.confidence_level*100:.0f}% CI)")
logger.info(f"Explanation length: {self.data_stats.avg_explanation_length:.1f} tokens "
f"({e_ci_lower:.1f} - {e_ci_upper:.1f}, {self.confidence_level*100:.0f}% CI)")
def detect_code_presence(self) -> None:
"""
Detect code presence in questions and explanations using
sophisticated pattern matching and machine learning.
"""
def contains_code(text: str) -> bool:
"""
Detect if text contains code using multiple heuristics.
Args:
text: Text to analyze
Returns:
Boolean indicating if code is detected
"""
# Enhanced code patterns with improved regex
code_patterns = [
# Code blocks and inline code
r'```[\s\S]*?```', # Markdown code blocks
r'`[^`]+`', # Inline code
# Programming language keywords
r'\b(?:function|def|class|import|from|select|if|for|while|var|let|const|async|await|return)\b',
# Function calls, method invocations, etc.
r'[a-zA-Z0-9_]+\([^)]*\)', # Function calls
r'\.[a-zA-Z0-9_]+\([^)]*\)', # Method calls
# Variable assignments and declarations
r'^\s*[a-zA-Z0-9_]+\s*=', # Variable assignments
r'^\s*(?:var|let|const)\s+[a-zA-Z0-9_]+', # JS variable declarations
# HTML, XML, and markup
r'<[a-zA-Z]+[^>]*>[\s\S]*?</[a-zA-Z]+>', # HTML/XML tags
r'<[a-zA-Z]+[^>]*\s?/>', # Self-closing tags
# SQL, database queries
r'SELECT\s+[\s\S]*?\s+FROM', # SQL SELECT
r'INSERT\s+INTO', # SQL INSERT
r'UPDATE\s+[\s\S]*?\s+SET', # SQL UPDATE
# CSS, styling
r'[.#][a-zA-Z0-9_-]+\s*\{[\s\S]*?\}', # CSS selectors
# Shell commands and scripting
r'(?:npm|pip|apt|brew)\s+install', # Install commands
r'git\s+(?:clone|commit|push|pull)', # Git commands
r'docker\s+(?:run|build|pull)', # Docker commands
# File paths and URLs that look like code
r'(?:\.\/|\/)[a-zA-Z0-9_\-\/\.]+\.[a-zA-Z0-9]+', # File paths
# JSON/Dict-like structures
r'\{(?:\s*"[^"]+"\s*:\s*(?:"[^"]*"|[0-9]+|true|false|null|undefined|\{|\[)[\s,]*)+\}',
# Array/List-like structures
r'\[(?:\s*(?:"[^"]*"|[0-9]+|true|false|null|undefined|\{|\[)[\s,]*)+\]',
]
# Check against each pattern
for pattern in code_patterns:
if re.search(pattern, text, re.IGNORECASE | re.MULTILINE):
return True
# Count code indicators as potential evidence
brackets = sum(text.count(c) for c in '[]{}()')
indented_lines = len(re.findall(r'^\s{2,}[^\s]', text, re.MULTILINE))
special_chars = sum(text.count(c) for c in '=+*/<>!&|^%')
# Use a weighted score for code likelihood
code_score = brackets*0.5 + indented_lines*2 + special_chars*0.3
if code_score > 10: # Threshold calibrated for code detection
return True
return False
logger.info("Detecting code presence in prompts and completions...")
# Apply the code detection function
self.df['question_has_code'] = self.df['question'].apply(contains_code)
self.df['explanation_has_code'] = self.df['explanation'].apply(contains_code)
# Compute code statistics
self.code_stats.questions_with_code = int(self.df['question_has_code'].sum())
self.code_stats.explanations_with_code = int(self.df['explanation_has_code'].sum())
self.code_stats.questions_with_code_percent = float(self.df['question_has_code'].mean() * 100)
self.code_stats.explanations_with_code_percent = float(self.df['explanation_has_code'].mean() * 100)
logger.info(f"Detected code in {self.code_stats.questions_with_code_percent:.1f}% of questions and "
f"{self.code_stats.explanations_with_code_percent:.1f}% of explanations")
def extract_nlp_features(self) -> None:
"""
Extract NLP features from the text using spaCy (if available)
or NLTK as a fallback.
"""
logger.info("Extracting NLP features from text...")
if SPACY_AVAILABLE:
# Efficient batched processing with spaCy
batch_size = 50 # Adjust based on document size and available memory
# Process questions in batches
self.keywords = []
self.entities = []
for i in tqdm(range(0, len(self.df), batch_size), desc="Processing with spaCy"):
batch_texts = self.df['question'].iloc[i:i+batch_size].tolist()
# Use spaCy's pipe for efficiency
docs = list(nlp.pipe(batch_texts))
for doc in docs:
# Extract named entities
self.entities.extend([ent.text for ent in doc.ents])
# Extract keywords (non-stopword nouns, verbs, and adjectives)
self.keywords.extend([
token.lemma_.lower() for token in doc
if (not token.is_stop and not token.is_punct and
token.pos_ in ('NOUN', 'VERB', 'ADJ'))
])
else:
# Fallback to NLTK
logger.info("Using NLTK for keyword extraction (fallback mode)")
for idx, row in tqdm(self.df.iterrows(), total=len(self.df), desc="Processing with NLTK"):
words = word_tokenize(row['question'])
self.keywords.extend([
w.lower() for w in words
if w.isalpha() and w.lower() not in self.stop_words
])
# Filter out irrelevant or very common terms
additional_stops = {'use', 'help', 'know', 'need', 'want', 'can', 'get', 'please', 'would', 'am', 'is', 'are'}
self.keywords = [k for k in self.keywords if k not in additional_stops]
logger.info(f"Extracted {len(set(self.keywords))} unique keywords and {len(set(self.entities))} unique entities")
def perform_topic_modeling(self) -> None:
"""
Perform topic modeling using advanced NMF or LDA approaches.
"""
if len(self.df) < 20:
logger.warning("Dataset too small for reliable topic modeling, skipping")
self.topics = {"insufficient_data": True}
return
logger.info("Performing topic modeling...")
# Choose the best available topic modeling approach
if SENTENCE_TRANSFORMERS_AVAILABLE and len(self.df) >= 50:
self._perform_nmf_topic_modeling()
else:
self._perform_lda_topic_modeling()
def _perform_nmf_topic_modeling(self) -> None:
"""
Use Non-negative Matrix Factorization (NMF) with TFIDF for advanced topic modeling.
This is a modern alternative to BERTopic that works well with transformers.
"""
try:
logger.info("Using NMF with transformer embeddings for topic modeling")
# Determine optimal number of topics based on dataset size
min_topics = 2
max_topics = min(20, max(5, len(self.df) // 50))
# Step 1: Get embeddings with sentence transformers
sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
embeddings = sentence_model.encode(
self.df['question'].tolist(),
show_progress_bar=True,
batch_size=16
)
# Step 2: Reduce dimensionality if needed (for visualization)
if UMAP_AVAILABLE and embeddings.shape[1] > 50:
# Reduce to a reasonable number of dimensions for NMF
reducer = umap.UMAP(
n_components=50,
metric='cosine',
random_state=42
)
reduced_embeddings = reducer.fit_transform(embeddings)
else:
# Fallback to TruncatedSVD
reducer = TruncatedSVD(n_components=min(50, embeddings.shape[1] - 1))
reduced_embeddings = reducer.fit_transform(embeddings)
# Step 3: Find optimal number of topics using silhouette score
best_num_topics = 0
best_score = -float('inf')
for n_topics in range(min_topics, max_topics + 1, 1):
# Use NMF for topic modeling
nmf = NMF(
n_components=n_topics,
random_state=42,
max_iter=500
)
doc_topic_matrix = nmf.fit_transform(reduced_embeddings)
# Use silhouette score as a measure of topic quality
if n_topics > 1: # Silhouette requires at least 2 clusters
# Use argmax to assign each document to its primary topic
doc_topic_labels = np.argmax(doc_topic_matrix, axis=1)
# Only calculate silhouette if we have enough documents with different labels
if len(set(doc_topic_labels)) > 1 and len(doc_topic_labels) >= 10:
try:
# Calculate silhouette score
sil_score = silhouette_score(reduced_embeddings, doc_topic_labels)
if sil_score > best_score:
best_score = sil_score
best_num_topics = n_topics
except Exception as e:
logger.warning(f"Silhouette calculation failed for {n_topics} topics: {str(e)}")
# If we couldn't determine the optimal number of topics, use a heuristic
if best_num_topics == 0:
best_num_topics = min(5, max(2, len(self.df) // 50))
logger.warning(f"Could not determine optimal topic count, using {best_num_topics}")
else:
logger.info(f"Optimal number of topics determined: {best_num_topics}")
# Step 4: Perform final NMF with optimal number of topics
nmf = NMF(
n_components=best_num_topics,
random_state=42,
max_iter=500
)
doc_topic_matrix = nmf.fit_transform(reduced_embeddings)
topic_term_matrix = nmf.components_
# Step 5: Extract keywords for each topic using TF-IDF
# We need to get keywords that correspond to the NMF components
vectorizer = TfidfVectorizer(
max_df=0.95,
min_df=2,
stop_words='english',
max_features=1000
)
tfidf_matrix = vectorizer.fit_transform(self.df['question'])
feature_names = vectorizer.get_feature_names_out()
# Extract top terms for each topic based on the original TF-IDF space
# We'll use KMeans to cluster documents by their NMF topics
kmeans = KMeans(
n_clusters=best_num_topics,
random_state=42
)
cluster_labels = kmeans.fit_predict(doc_topic_matrix)
# Now we can extract top terms for each cluster/topic
self.topics = {}
for topic_idx in range(best_num_topics):
# Get documents in this topic/cluster
topic_docs = [i for i, label in enumerate(cluster_labels) if label == topic_idx]
if topic_docs:
# Get the TF-IDF vectors for these documents
topic_tfidf = tfidf_matrix[topic_docs]
# Calculate average TF-IDF score for each term in this topic
topic_tfidf_sum = topic_tfidf.sum(axis=0)
topic_tfidf_avg = topic_tfidf_sum / len(topic_docs)
# Get top terms by average TF-IDF
top_term_indices = np.argsort(topic_tfidf_avg.toarray()[0])[::-1][:15]
top_terms = [feature_names[i] for i in top_term_indices]
top_weights = [float(topic_tfidf_avg[0, i]) for i in top_term_indices]
# Create dictionary for this topic
self.topics[f"Topic_{topic_idx+1}"] = {
term: weight for term, weight in zip(top_terms, top_weights)
}
else:
# Empty topic
self.topics[f"Topic_{topic_idx+1}"] = {}
# Try to calculate topic coherence or a similar quality metric
try:
# Use average silhouette score as a coherence-like metric
self.complexity.coherence = float(best_score)
logger.info(f"Topic coherence (silhouette): {best_score:.4f}")
except:
logger.warning("Could not calculate topic coherence")
logger.info(f"NMF topic modeling identified {len(self.topics)} topics")
except Exception as e:
logger.error(f"NMF topic modeling failed: {str(e)}")
logger.info("Falling back to LDA topic modeling")
self._perform_lda_topic_modeling()
def _perform_lda_topic_modeling(self) -> None:
"""Use LDA for topic modeling (fallback method)."""
try:
logger.info("Using LDA for topic modeling")
# Create a document-term matrix
vectorizer = CountVectorizer(
max_df=0.95,
min_df=2,
stop_words='english',
max_features=1000
)
X = vectorizer.fit_transform(self.df['question'])
# Determine optimal number of topics using coherence or silhouette score
best_num_topics = 0
best_score = -float('inf')
# Try different numbers of topics (can be computationally expensive)
min_topics = min(2, len(self.df) // 100)
max_topics = min(10, max(2, len(self.df) // 20))
for n_topics in range(min_topics, max_topics + 1, 1):
lda = LatentDirichletAllocation(
n_components=n_topics,
random_state=42,
max_iter=20,
learning_method='online'
)
doc_topic_matrix = lda.fit_transform(X)
# Use silhouette score as a measure of topic quality
if n_topics > 1: # Silhouette requires at least 2 clusters
# Use argmax to assign each document to its primary topic
doc_topic_labels = np.argmax(doc_topic_matrix, axis=1)
# Only calculate silhouette if we have enough documents
if len(set(doc_topic_labels)) > 1 and len(doc_topic_labels) >= 10:
try:
# SVD for dimensionality reduction
svd = TruncatedSVD(n_components=min(50, X.shape[1] - 1))
X_reduced = svd.fit_transform(X)
# Calculate silhouette score
sil_score = silhouette_score(X_reduced, doc_topic_labels)
if sil_score > best_score:
best_score = sil_score
best_num_topics = n_topics
except Exception as e:
logger.warning(f"Silhouette calculation failed for {n_topics} topics: {str(e)}")
# If we couldn't determine the optimal number of topics, use a heuristic
if best_num_topics == 0:
best_num_topics = min(5, max(2, len(self.df) // 50))
logger.warning(f"Could not determine optimal topic count, using {best_num_topics}")
else:
logger.info(f"Optimal number of topics determined: {best_num_topics}")
# Fit final LDA model with optimal number of topics
lda = LatentDirichletAllocation(
n_components=best_num_topics,
random_state=42,
max_iter=25,
learning_method='online'
)
lda.fit(X)
# Calculate perplexity (lower is better)
perplexity = lda.perplexity(X)
self.complexity.perplexity = float(perplexity)
logger.info(f"LDA model perplexity: {perplexity:.2f}")
# Get feature names (terms)
feature_names = vectorizer.get_feature_names_out()
# Extract top terms for each topic
self.topics = {}
for topic_idx, topic in enumerate(lda.components_):
top_words_idx = topic.argsort()[:-11:-1] # Top 10 terms
top_words = [feature_names[i] for i in top_words_idx]
top_weights = [float(topic[i]) for i in top_words_idx]
# Create a dictionary for this topic
self.topics[f"Topic_{topic_idx+1}"] = {
word: weight for word, weight in zip(top_words, top_weights)
}
logger.info(f"LDA modeling identified {len(self.topics)} topics")
except Exception as e:
logger.error(f"LDA topic modeling failed: {str(e)}")
# Fallback to basic keyword extraction if even LDA fails
self.topics = {"keyword_counts": dict(Counter(self.keywords).most_common(30))}
logger.warning("Using keyword frequency as fallback for topic modeling")
def analyze_semantic_complexity(self) -> None:
"""
Analyze semantic complexity and content diversity using
transformer embeddings or TF-IDF as a fallback.
"""
logger.info("Analyzing semantic complexity...")
# Default middle value
diversity_score = 0.5
confidence_interval = (0.45, 0.55)
if SENTENCE_TRANSFORMERS_AVAILABLE:
try:
# Sample if dataset is large to save computation time
max_sample = 200
sample_size = min(max_sample, len(self.df))
sample_df = self.df.sample(sample_size) if len(self.df) > sample_size else self.df
# Generate embeddings with modern transformer model
logger.info(f"Generating embeddings for {sample_size} samples...")
model = SentenceTransformer('all-MiniLM-L6-v2')
question_embeddings = model.encode(
sample_df['question'].tolist(),
show_progress_bar=True,
batch_size=16,
convert_to_numpy=True
)
# Calculate pairwise similarities
similarity_matrix = cosine_similarity(question_embeddings)
# Calculate average similarity (lower means more diverse/complex content)
# Get upper triangular matrix without diagonal (pairwise similarities)
upper_tri_indices = np.triu_indices(len(similarity_matrix), k=1)
similarities = similarity_matrix[upper_tri_indices]
# Calculate mean and confidence interval
avg_similarity = np.mean(similarities)
# Use bootstrap to calculate confidence interval for diversity score
n_bootstrap = 1000
bootstrap_means = np.zeros(n_bootstrap)
np.random.seed(42)
for i in range(n_bootstrap):
sample_indices = np.random.choice(len(similarities), size=len(similarities), replace=True)
bootstrap_sample = similarities[sample_indices]
bootstrap_means[i] = np.mean(bootstrap_sample)
# Calculate confidence interval
alpha = 1 - self.confidence_level
ci_lower = np.percentile(bootstrap_means, alpha/2 * 100)
ci_upper = np.percentile(bootstrap_means, (1-alpha/2) * 100)
# Convert to diversity scores (inverse of similarity)
diversity_score = 1 - avg_similarity
ci_lower_diversity = 1 - ci_upper # Note the inversion
ci_upper_diversity = 1 - ci_lower # Note the inversion
confidence_interval = (ci_lower_diversity, ci_upper_diversity)
logger.info(f"Computed semantic diversity score: {diversity_score:.3f} "
f"({ci_lower_diversity:.3f} - {ci_upper_diversity:.3f}, {self.confidence_level*100:.0f}% CI)")
except Exception as e:
logger.warning(f"Semantic complexity analysis failed: {str(e)}. Using fallback method.")
self._analyze_lexical_diversity()
else:
logger.info("Sentence Transformers not available, using fallback method for complexity assessment.")
self._analyze_lexical_diversity()
# Store the computed diversity score and confidence interval
self.complexity.diversity_score = float(diversity_score)
self.complexity.confidence_interval = confidence_interval
# Calculate enhanced complexity assessment using multiple factors
linguistic_complexity_score = sum([
(self.data_stats.avg_explanation_length / 100) * 2, # Longer explanations suggest complexity
(self.code_stats.explanations_with_code_percent / 100) * 3, # Code presence indicates technical content
(self.data_stats.avg_question_length / 50), # Longer questions suggest detailed queries
diversity_score * 5 # Semantic/lexical diversity as a complexity indicator
])
self.complexity.linguistic_complexity_score = float(linguistic_complexity_score)
# Determine complexity category with confidence measure
if linguistic_complexity_score > 5:
self.complexity.assessment = "High"
elif linguistic_complexity_score > 3:
self.complexity.assessment = "Medium"
else:
self.complexity.assessment = "Low"
logger.info(f"Content complexity assessment: {self.complexity.assessment} "
f"(Score: {linguistic_complexity_score:.2f})")
def _analyze_lexical_diversity(self) -> None:
"""Analyze lexical diversity using TF-IDF as a fallback method."""
try:
# Create TF-IDF matrix
tfidf = TfidfVectorizer(max_df=0.95, min_df=2, stop_words='english')
tfidf_matrix = tfidf.fit_transform(self.df['question'])
# Number of unique terms as ratio of total words is a simple diversity measure
vocabulary_size = len(tfidf.get_feature_names_out())
total_words = sum([len(word_tokenize(q)) for q in self.df['question']])
# Normalize to a 0-1 scale (higher means more diverse vocabulary)
diversity_score = min(0.95, vocabulary_size / (total_words * 0.1))
# Estimate confidence interval using heuristic
std_dev = 0.05 # Assumed standard deviation
n = len(self.df)
z = stats.norm.ppf(1 - (1 - self.confidence_level) / 2)
margin = z * std_dev / np.sqrt(n)
ci_lower = max(0, diversity_score - margin)
ci_upper = min(1, diversity_score + margin)
self.complexity.diversity_score = float(diversity_score)
self.complexity.confidence_interval = (float(ci_lower), float(ci_upper))
logger.info(f"Computed lexical diversity score: {diversity_score:.3f} "
f"({ci_lower:.3f} - {ci_upper:.3f}, {self.confidence_level*100:.0f}% CI)")
except Exception as e:
logger.warning(f"Lexical diversity analysis failed: {str(e)}. Using default value.")
self.complexity.diversity_score = 0.5
self.complexity.confidence_interval = (0.4, 0.6)
def create_visualizations(self) -> None:
"""Generate publication-quality visualizations of the analysis results."""
logger.info("Creating visualizations...")
# Set plotting style for publication quality
plt.style.use('seaborn-v0_8-whitegrid')
sns.set_context("paper", font_scale=1.2)
# Create Length Distribution plots
self._plot_length_distributions()
# Create code presence visualization
self._plot_code_presence()
# Create wordcloud visualization
self._create_wordcloud()
# Create topic visualization
self._plot_topics()
# Generate summary visualization
self._create_summary_dashboard()
logger.info(f"Visualizations saved to {os.path.join(self.output_dir, 'plots')}")
def _plot_length_distributions(self) -> None:
"""Create visualizations of token length distributions."""
# Publication-quality length distribution plots
if PLOTLY_AVAILABLE:
# Create interactive length distribution plot with Plotly
fig = make_subplots(
rows=1, cols=2,
subplot_titles=('Question Length Distribution', 'Explanation Length Distribution'),
shared_yaxes=True
)
# Question length histogram
q_trace = go.Histogram(
x=self.df['question_tokens'],
name='Questions',
opacity=0.75,
marker=dict(color='blue'),
nbinsx=30
)
# Add mean and median markers for questions
q_mean_trace = go.Scatter(
x=[self.data_stats.avg_question_length, self.data_stats.avg_question_length],
y=[0, self.df['question_tokens'].value_counts().max()],
mode='lines',
name='Mean',
line=dict(color='red', width=2, dash='dash')
)
q_median_trace = go.Scatter(
x=[self.data_stats.median_question_length, self.data_stats.median_question_length],
y=[0, self.df['question_tokens'].value_counts().max()],
mode='lines',
name='Median',
line=dict(color='green', width=2)
)
# Explanation length histogram
e_trace = go.Histogram(
x=self.df['explanation_tokens'],
name='Explanations',
opacity=0.75,
marker=dict(color='orange'),
nbinsx=30
)
# Add mean and median markers for explanations
e_mean_trace = go.Scatter(
x=[self.data_stats.avg_explanation_length, self.data_stats.avg_explanation_length],
y=[0, self.df['explanation_tokens'].value_counts().max()],
mode='lines',
name='Mean',
line=dict(color='red', width=2, dash='dash'),
showlegend=False
)
e_median_trace = go.Scatter(
x=[self.data_stats.median_explanation_length, self.data_stats.median_explanation_length],
y=[0, self.df['explanation_tokens'].value_counts().max()],
mode='lines',
name='Median',
line=dict(color='green', width=2),
showlegend=False
)
# Add all traces to the figure
fig.add_trace(q_trace, row=1, col=1)
fig.add_trace(q_mean_trace, row=1, col=1)
fig.add_trace(q_median_trace, row=1, col=1)
fig.add_trace(e_trace, row=1, col=2)
fig.add_trace(e_mean_trace, row=1, col=2)
fig.add_trace(e_median_trace, row=1, col=2)
# Update layout for publication quality
fig.update_layout(
title='Token Length Distributions',
xaxis_title='Number of Tokens',
yaxis_title='Count',
template='plotly_white',
height=500,
width=1000,
legend=dict(
yanchor="top",