Spaces:
Running
Running
YanBoChen
commited on
Commit
·
775f8ea
1
Parent(s):
922ed80
Remove obsolete embedding and index files; add comprehensive embedding test analysis and validation suite
Browse files- tests/embedding_test_analysis.md +355 -0
- tests/test_embedding_validation.py +213 -0
tests/embedding_test_analysis.md
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Embedding Test Analysis Report
|
| 2 |
+
|
| 3 |
+
## 1. Dataset Overview
|
| 4 |
+
|
| 5 |
+
### 1.1 Data Dimensions
|
| 6 |
+
- Emergency Dataset: 27,493 chunks × 768 dimensions
|
| 7 |
+
- Treatment Dataset: 82,378 chunks × 768 dimensions
|
| 8 |
+
- Total Chunks: 109,871
|
| 9 |
+
|
| 10 |
+
### 1.2 Embedding Statistics
|
| 11 |
+
|
| 12 |
+
**Emergency Embeddings:**
|
| 13 |
+
- Value Range: -3.246 to 3.480
|
| 14 |
+
- Mean: -0.017
|
| 15 |
+
- Standard Deviation: 0.462
|
| 16 |
+
|
| 17 |
+
**Treatment Embeddings:**
|
| 18 |
+
- Value Range: -3.686 to 3.505
|
| 19 |
+
- Mean: -0.017
|
| 20 |
+
- Standard Deviation: 0.472
|
| 21 |
+
|
| 22 |
+
**Analysis:**
|
| 23 |
+
- Both datasets have similar statistical properties
|
| 24 |
+
- Mean values are centered around zero (-0.017)
|
| 25 |
+
- Standard deviations are comparable (0.462 vs 0.472)
|
| 26 |
+
- Treatment dataset has slightly wider range (-3.686 to 3.505 vs -3.246 to 3.480)
|
| 27 |
+
|
| 28 |
+
## 2. Model Performance
|
| 29 |
+
|
| 30 |
+
### 2.1 Self-Retrieval Test
|
| 31 |
+
- Test Size: 20 random samples
|
| 32 |
+
- Success Rate: 19/20 (95%)
|
| 33 |
+
- Failed Case: Index 27418
|
| 34 |
+
- Average Response Time: ~5ms per search
|
| 35 |
+
|
| 36 |
+
**Observations:**
|
| 37 |
+
- High success rate in self-retrieval (95%)
|
| 38 |
+
- One failure case needs investigation
|
| 39 |
+
- Search operations are consistently fast
|
| 40 |
+
|
| 41 |
+
### 2.2 Cross-Dataset Search Performance
|
| 42 |
+
|
| 43 |
+
**Test Queries:**
|
| 44 |
+
1. "What is the treatment protocol for acute myocardial infarction?"
|
| 45 |
+
2. "How to manage severe chest pain with difficulty breathing?"
|
| 46 |
+
3. "What are the emergency procedures for anaphylactic shock?"
|
| 47 |
+
|
| 48 |
+
**Key Findings:**
|
| 49 |
+
- Each query returns top-5 results from both datasets
|
| 50 |
+
- Results show semantic understanding (not just keyword matching)
|
| 51 |
+
- First sentences provide good context for relevance assessment
|
| 52 |
+
|
| 53 |
+
## 3. System Performance
|
| 54 |
+
|
| 55 |
+
### 3.1 Response Times
|
| 56 |
+
- Model Loading: ~3 seconds
|
| 57 |
+
- Embedding Validation: ~0.5 seconds
|
| 58 |
+
- Search Operations: 0.1-0.2 seconds per query
|
| 59 |
+
|
| 60 |
+
### 3.2 Resource Usage
|
| 61 |
+
- Model loaded on MPS (Metal Performance Shaders)
|
| 62 |
+
- Efficient memory usage for large datasets
|
| 63 |
+
- Fast vector operations
|
| 64 |
+
|
| 65 |
+
## 4. Recommendations
|
| 66 |
+
|
| 67 |
+
### 4.1 Immediate Improvements
|
| 68 |
+
1. Investigate failed self-retrieval case (index 27418)
|
| 69 |
+
2. Consider caching frequently accessed embeddings
|
| 70 |
+
3. Add more diverse test queries
|
| 71 |
+
|
| 72 |
+
### 4.2 Future Enhancements
|
| 73 |
+
1. Implement hybrid search (combine with BM25)
|
| 74 |
+
2. Add relevance scoring mechanism
|
| 75 |
+
3. Consider domain-specific test cases
|
| 76 |
+
|
| 77 |
+
## 5. Log Analysis
|
| 78 |
+
|
| 79 |
+
### 5.1 Log Structure
|
| 80 |
+
```
|
| 81 |
+
timestamp - level - message
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
### 5.2 Log Levels Used
|
| 85 |
+
- DEBUG: Detailed operation info
|
| 86 |
+
- INFO: General progress and results
|
| 87 |
+
- WARNING: Non-critical issues
|
| 88 |
+
- ERROR: Critical failures
|
| 89 |
+
|
| 90 |
+
### 5.3 Key Log Categories
|
| 91 |
+
1. **Initialization Logs:**
|
| 92 |
+
- Path configurations
|
| 93 |
+
- Model loading
|
| 94 |
+
- Dataset loading
|
| 95 |
+
|
| 96 |
+
2. **Performance Logs:**
|
| 97 |
+
- Search operations
|
| 98 |
+
- Response times
|
| 99 |
+
- Success/failure counts
|
| 100 |
+
|
| 101 |
+
3. **Error Logs:**
|
| 102 |
+
- Failed searches
|
| 103 |
+
- Validation errors
|
| 104 |
+
- Connection issues
|
| 105 |
+
|
| 106 |
+
### 5.4 Notable Log Patterns
|
| 107 |
+
- Regular HTTPS connections to HuggingFace
|
| 108 |
+
- Consistent search operation timing
|
| 109 |
+
- Clear error messages for failures
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
<!-- split -->
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# 🧪 Embedding Test Analysis Report | 向量嵌入測試分析報告
|
| 116 |
+
|
| 117 |
+
## 1. Dataset Overview | 資料集總覽
|
| 118 |
+
|
| 119 |
+
### 1.1 Data Dimensions | 資料維度
|
| 120 |
+
- **Emergency Dataset**: 27,493 chunks × 768 dimensions
|
| 121 |
+
- **Treatment Dataset**: 82,378 chunks × 768 dimensions
|
| 122 |
+
- **Total Chunks**: 109,871
|
| 123 |
+
|
| 124 |
+
### 1.2 Embedding Statistics | 向量統計
|
| 125 |
+
**Emergency Embeddings 緊急資料集嵌入向量:**
|
| 126 |
+
- Value Range 範圍: -3.246 ~ 3.480
|
| 127 |
+
- Mean 平均值: -0.017
|
| 128 |
+
- Std 標準差: 0.462
|
| 129 |
+
|
| 130 |
+
**Treatment Embeddings 治療資料集嵌入向量:**
|
| 131 |
+
- Value Range 範圍: -3.686 ~ 3.505
|
| 132 |
+
- Mean 平均值: -0.017
|
| 133 |
+
- Std 標準差: 0.472
|
| 134 |
+
|
| 135 |
+
**Analysis 分析:**
|
| 136 |
+
- 兩組資料集中向量分布接近,平均值均接近 0
|
| 137 |
+
- Treatment 資料集範圍稍寬,可能涵蓋更廣語意
|
| 138 |
+
|
| 139 |
+
---
|
| 140 |
+
|
| 141 |
+
## 2. Model Performance | 模型檢索表現
|
| 142 |
+
|
| 143 |
+
### 2.1 Self-Retrieval Test | 自我召回測試
|
| 144 |
+
- 測試數量 Test Size: 20
|
| 145 |
+
- 成功率 Success Rate: **95% (19/20)**
|
| 146 |
+
- 失敗案例 Failed Index: `27418`
|
| 147 |
+
- 平均搜尋時間 Avg Search Time: ~5ms
|
| 148 |
+
|
| 149 |
+
**Observation 觀察:**
|
| 150 |
+
- 自我召回成功率高,顯示索引構建準確
|
| 151 |
+
- 可進一步針對失敗樣本檢查切 chunk 是否過短
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
<!-- Details -->
|
| 155 |
+
|
| 156 |
+
# 🔍 Embedding Search Analysis Report (Emergency vs Treatment)
|
| 157 |
+
|
| 158 |
+
## 📊 Overall Summary
|
| 159 |
+
|
| 160 |
+
| Query | Emergency Results | Treatment Results | Summary Comment |
|
| 161 |
+
|---------------------------------------------------------|------------------------|------------------------|-----------------------------------------------|
|
| 162 |
+
| 1️⃣ Treatment for Acute Myocardial Infarction | ✅ Matched well | ✅ Highly relevant | Relevant guidelines retrieved from both sets |
|
| 163 |
+
| 2️⃣ Management of Severe Chest Pain with Dyspnea | ⚠️ Redundant, not focused | ⚠️ Vague and general | Lacks actionable steps, contains repetition |
|
| 164 |
+
| 3️⃣ Emergency Procedures for Anaphylactic Shock | ⚠️ Off-topic | ✅ Precise and relevant | Emergency off-topic, but Treatment is strong |
|
| 165 |
+
|
| 166 |
+
---
|
| 167 |
+
|
| 168 |
+
## ��� Detailed Query Analysis
|
| 169 |
+
|
| 170 |
+
### ✅ 1. `What is the treatment protocol for acute myocardial infarction?`
|
| 171 |
+
|
| 172 |
+
#### 📌 Emergency Dataset:
|
| 173 |
+
- `E-2 ~ E-4` mention guidelines, STEMI, PCI.
|
| 174 |
+
- Distances range from `0.833 ~ 0.842` → valid.
|
| 175 |
+
- `E-3` is a long guideline chunk → ideal RAG candidate.
|
| 176 |
+
|
| 177 |
+
✅ Conclusion: Emergency subset performs well, keyword chunking effective.
|
| 178 |
+
|
| 179 |
+
#### 📌 Treatment Dataset:
|
| 180 |
+
- `T-1` and `T-2` directly address the question with guideline phrases.
|
| 181 |
+
- `distance ~0.813` → strong semantic match.
|
| 182 |
+
- `T-5` is shorter but still contains “AMI”.
|
| 183 |
+
|
| 184 |
+
✅ Conclusion: Treatment retrieval is highly effective.
|
| 185 |
+
|
| 186 |
+
---
|
| 187 |
+
|
| 188 |
+
### ⚠️ 2. `How to manage severe chest pain with difficulty breathing?`
|
| 189 |
+
|
| 190 |
+
#### 📌 Emergency Dataset:
|
| 191 |
+
- `E-1 ~ E-3` are identical dyspnea passages; no actionable steps.
|
| 192 |
+
- `E-4 ~ E-5` are general symptom overviews, not acute response protocols.
|
| 193 |
+
|
| 194 |
+
⚠️ Issue: Semantic match exists, but lacks procedural content.
|
| 195 |
+
⚠️ Repetition indicates Annoy might be over-focused on a narrow cluster.
|
| 196 |
+
|
| 197 |
+
#### 📌 Treatment Dataset:
|
| 198 |
+
- `T-1 ~ T-3` mention dyspnea and chest pain but are mostly patient descriptions.
|
| 199 |
+
- `T-4` hints at emergency care for asthma but still lacks clarity.
|
| 200 |
+
|
| 201 |
+
⚠️ Conclusion: This query needs better symptom-action co-occurrence modeling.
|
| 202 |
+
|
| 203 |
+
---
|
| 204 |
+
|
| 205 |
+
### ⚠️ 3. `What are the emergency procedures for anaphylactic shock?`
|
| 206 |
+
|
| 207 |
+
#### 📌 Emergency Dataset:
|
| 208 |
+
- `E-1 ~ E-2`: irrelevant or truncated.
|
| 209 |
+
- `E-3`: mentions management during anesthesia → partial match.
|
| 210 |
+
- `E-4 ~ E-5`: just list multiple shock types; no protocol info.
|
| 211 |
+
|
| 212 |
+
❌ Emergency dataset lacks focused content on this topic.
|
| 213 |
+
|
| 214 |
+
#### 📌 Treatment Dataset:
|
| 215 |
+
- `T-1`: explicitly lists epinephrine, oxygen, IV fluids, corticosteroids → ✅ ideal
|
| 216 |
+
- `T-2`: confirms emergency drug prep
|
| 217 |
+
- `T-3 ~ T-5`: all recognize anaphylactic shock
|
| 218 |
+
|
| 219 |
+
✅ Conclusion: Treatment subset captures this case very accurately.
|
| 220 |
+
|
| 221 |
+
---
|
| 222 |
+
|
| 223 |
+
## 📏 Distance Threshold Reference
|
| 224 |
+
|
| 225 |
+
| Distance Value Range | Interpretation |
|
| 226 |
+
|----------------------|--------------------------------------------|
|
| 227 |
+
| `< 0.80` | Very strong match (almost identical) |
|
| 228 |
+
| `0.80 ~ 0.86` | Acceptable semantic match |
|
| 229 |
+
| `> 0.90` | Weak relevance, possibly off-topic chunks |
|
| 230 |
+
|
| 231 |
+
---
|
| 232 |
+
|
| 233 |
+
## 🧰 Recommendations Based on Findings
|
| 234 |
+
|
| 235 |
+
| Issue Type | Suggested Solution |
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
(genAIvenv) yanbochen@YanBos-MacBook-Pro tests % python test_embedding_validation.py
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
=== Query: What is the treatment protocol for acute myocardial infarction? ===
|
| 242 |
+
Batches: 100%|██████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 6.65it/s]
|
| 243 |
+
|
| 244 |
+
Emergency Dataset Results:
|
| 245 |
+
|
| 246 |
+
E-1 (distance: 0.826):
|
| 247 |
+
myocardial infarction, white [ / bib _ ref ].
|
| 248 |
+
|
| 249 |
+
E-2 (distance: 0.833):
|
| 250 |
+
the management of acute myocardial infarction : guidelines and audit standards successful management of acute myocardial infarction depends in the first instance on the patient recognising the symptoms and seeking help as quickly as possible.
|
| 251 |
+
|
| 252 |
+
E-3 (distance: 0.836):
|
| 253 |
+
sandbox : stemi # 2017 esc guidelines for the management of acute myocardial infarction in patients presenting with st - segment elevation # # changes in recommendations # # what is new in 2017 guidelines on ami - stemi? # # ami - stemi - 2017 new recommendations # acc / aats / aha / ase / asnc / scai / scct / sts 2016 appropriate use criteria for coronary revascularization in patients with acute coronary syndromes # # stemi — immediate revascularization by pci # # stemi — initial treatment by fibrinolytic therapy # # stemi — revascularization of nonculprit artery during the initial hospitalization # 2017 aha / acc clinical performance and quality measures for adults with st - elevation and non – st - elevation myocardial infarction # # revised stemi and nstemi measures # # revised stemi and nstemi measures.
|
| 254 |
+
|
| 255 |
+
E-4 (distance: 0.842):
|
| 256 |
+
stemi resident survival guide # overview st elevation myocardial infarction ( stemi ) is a syndrome characterized by the presence of symptoms of myocardial ischemia associated with persistent st elevation on electrocardiogram and elevated cardiac enzymes.
|
| 257 |
+
|
| 258 |
+
E-5 (distance: 0.879):
|
| 259 |
+
# pre - discharge care abbreviations : ace : angiotensin converting enzyme ; lvef : left ventricular ejection fraction ; mi : myocardial infarction ; pci : percutaneous coronary intervention ; po : per os ; stemi : st elevation myocardial infarction ; vf : ventricular fibrillation ; vt : ventricular tachycardia # long term management abbreviations : ace : angiotensin converting enzyme ; arb : angiotensin receptor blocker ; mi : myocardial infarction # do ' s - a pre - hospital ecg is recommended.
|
| 260 |
+
|
| 261 |
+
Treatment Dataset Results:
|
| 262 |
+
|
| 263 |
+
T-1 (distance: 0.813):
|
| 264 |
+
intain the standard of care and timely access of patients with ACS, including acute myocardial infarction (AMI), to reperfusion therapy.
|
| 265 |
+
|
| 266 |
+
T-2 (distance: 0.825):
|
| 267 |
+
The Management of Acute Myocardial Infarction: Guidelines and Audit Standards
|
| 268 |
+
|
| 269 |
+
Successful management of acute myocardial infarction.
|
| 270 |
+
|
| 271 |
+
T-3 (distance: 0.854):
|
| 272 |
+
fined as STEMI, NSTEMI or unstable angina.
|
| 273 |
+
|
| 274 |
+
T-4 (distance: 0.869):
|
| 275 |
+
Japan, there are no clear guidelines focusing on procedural aspect of the standardized care.
|
| 276 |
+
|
| 277 |
+
T-5 (distance: 0.879):
|
| 278 |
+
ients with acute myocardial infarction (AMI).
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
=== Query: How to manage severe chest pain with difficulty breathing? ===
|
| 282 |
+
Batches: 100%|██████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 47.76it/s]
|
| 283 |
+
|
| 284 |
+
Emergency Dataset Results:
|
| 285 |
+
|
| 286 |
+
E-1 (distance: 0.848):
|
| 287 |
+
shortness of breath resident survival guide # overview dyspnea is a symptom, it must generally be distinguished from signs that clinicians typically invoke as evidence of respiratory distress, such as tachypnea, use of accessory muscles, and intercostal retractions.
|
| 288 |
+
|
| 289 |
+
E-2 (distance: 0.849):
|
| 290 |
+
shortness of breath resident survival guide # overview dyspnea is a symptom, it must generally be distinguished from signs that clinicians typically invoke as evidence of respiratory distress, such as tachypnea, use of accessory muscles, and intercostal retractions.
|
| 291 |
+
|
| 292 |
+
E-3 (distance: 0.852):
|
| 293 |
+
shortness of breath resident survival guide # overview dyspnea is a symptom, it must generally be distinguished from signs that clinicians typically invoke as evidence of respiratory distress, such as tachypnea, use of accessory muscles, and intercostal retractions.
|
| 294 |
+
|
| 295 |
+
E-4 (distance: 0.879):
|
| 296 |
+
sandbox : milan # overview dyspnea is the uncomfortable awareness of one ' s own breathing.
|
| 297 |
+
|
| 298 |
+
E-5 (distance: 0.879):
|
| 299 |
+
sandbox : milan # overview dyspnea is the uncomfortable awareness of one ' s own breathing.
|
| 300 |
+
|
| 301 |
+
Treatment Dataset Results:
|
| 302 |
+
|
| 303 |
+
T-1 (distance: 0.827):
|
| 304 |
+
lly cyanotic and clammy, and may experience dyspnea or chest pain from underperfusion 13 .
|
| 305 |
+
|
| 306 |
+
T-2 (distance: 0.868):
|
| 307 |
+
acterized by a worsening of the patient’s respiratory symptoms (baseline dyspnea, cough, and/or sputum production) that is beyond normal day-to-day variations and leads to a change in medication.
|
| 308 |
+
|
| 309 |
+
T-3 (distance: 0.872):
|
| 310 |
+
ally cyanotic and clammy, and may experience dyspnea or chest pain from underperfusion 13.
|
| 311 |
+
|
| 312 |
+
T-4 (distance: 0.898):
|
| 313 |
+
ce used to test breathing) results show your breathing problems are worsening
|
| 314 |
+
- you need to go to the emergency room for asthma treatment.
|
| 315 |
+
|
| 316 |
+
T-5 (distance: 0.898):
|
| 317 |
+
breathlessness in a person in the last days of life.
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
=== Query: What are the emergency procedures for anaphylactic shock? ===
|
| 321 |
+
Batches: 100%|██████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 57.16it/s]
|
| 322 |
+
|
| 323 |
+
Emergency Dataset Results:
|
| 324 |
+
|
| 325 |
+
E-1 (distance: 0.924):
|
| 326 |
+
the other.
|
| 327 |
+
|
| 328 |
+
E-2 (distance: 0.943):
|
| 329 |
+
ic defibrillation.
|
| 330 |
+
|
| 331 |
+
E-3 (distance: 0.946):
|
| 332 |
+
suspected anaphylactic reactions associated with anaesthesia # # summary ( 1 ) the aagbi has published guidance on management of anaphylaxis during anaesthesia in.
|
| 333 |
+
|
| 334 |
+
E-4 (distance: 0.952):
|
| 335 |
+
- gastrointestinal bleeding - perforated peptic ulcer - post - procedural or post - surgical - retroperitoneal hemorrhage - rupture ovarian cyst - trauma - distributive shock - sepsis - toxic shock syndrome - anaphylactic or anaphylactoid reaction - neurogenic shock - adrenal crisis # fire : focused initial rapid evaluation a focused initial rapid evaluation ( fire ) should be performed to identify patients in need of immediate intervention.
|
| 336 |
+
|
| 337 |
+
E-5 (distance: 0.954):
|
| 338 |
+
- surgical - retroperitoneal hemorrhage - rupture ovarian cyst - trauma - distributive shock - sepsis - toxic shock syndrome - anaphylactic or anaphylactoid reaction - neurogenic shock - adrenal crisis # fire : focused initial rapid evaluation a focused initial rapid evaluation ( fire ) should be performed to identify patients in need of immediate intervention.
|
| 339 |
+
|
| 340 |
+
Treatment Dataset Results:
|
| 341 |
+
|
| 342 |
+
T-1 (distance: 0.813):
|
| 343 |
+
ensitivity (anaphylactic) reactions require emergency treatment with epinephrine and other emergency measures, that may include airway management, oxygen, intravenous fluids, antihistamines, corticosteroids, and vasopressors as clinically indicated.
|
| 344 |
+
|
| 345 |
+
T-2 (distance: 0.833):
|
| 346 |
+
ave standard emergency treatments for hypersensitivity or anaphylactic reactions readily available in the operating room (e.
|
| 347 |
+
|
| 348 |
+
T-3 (distance: 0.838):
|
| 349 |
+
e, or systemic inflammation (anaphylactic shock).
|
| 350 |
+
|
| 351 |
+
T-4 (distance: 0.843):
|
| 352 |
+
ED AND APPROPRIATE THERAPY INSTITUTED.
|
| 353 |
+
|
| 354 |
+
T-5 (distance: 0.844):
|
| 355 |
+
UED AND APPROPRIATE THERAPY INSTITUTED.
|
tests/test_embedding_validation.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test suite for validating embeddings and ANNOY functionality.
|
| 3 |
+
This module ensures the quality of embeddings and the correctness of ANNOY search.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Tuple, List, Optional
|
| 12 |
+
from annoy import AnnoyIndex
|
| 13 |
+
from sentence_transformers import SentenceTransformer
|
| 14 |
+
|
| 15 |
+
class TestEmbeddingValidation:
|
| 16 |
+
def setup_class(self):
|
| 17 |
+
"""Initialize test environment with necessary data and models."""
|
| 18 |
+
# Setup logging
|
| 19 |
+
logging.basicConfig(
|
| 20 |
+
level=logging.DEBUG,
|
| 21 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 22 |
+
filename='embedding_validation.log'
|
| 23 |
+
)
|
| 24 |
+
self.logger = logging.getLogger(__name__)
|
| 25 |
+
|
| 26 |
+
# Define base paths
|
| 27 |
+
self.project_root = Path(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 28 |
+
self.models_dir = self.project_root / "models"
|
| 29 |
+
self.embeddings_dir = self.models_dir / "embeddings"
|
| 30 |
+
self.indices_dir = self.models_dir / "indices" / "annoy"
|
| 31 |
+
|
| 32 |
+
self.logger.info(f"Project root: {self.project_root}")
|
| 33 |
+
self.logger.info(f"Models directory: {self.models_dir}")
|
| 34 |
+
self.logger.info(f"Embeddings directory: {self.embeddings_dir}")
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
# Check directory existence
|
| 38 |
+
if not self.embeddings_dir.exists():
|
| 39 |
+
raise FileNotFoundError(f"Embeddings directory not found at: {self.embeddings_dir}")
|
| 40 |
+
if not self.indices_dir.exists():
|
| 41 |
+
raise FileNotFoundError(f"Indices directory not found at: {self.indices_dir}")
|
| 42 |
+
|
| 43 |
+
# Load embeddings
|
| 44 |
+
self.emergency_emb = np.load(self.embeddings_dir / "emergency_embeddings.npy")
|
| 45 |
+
self.treatment_emb = np.load(self.embeddings_dir / "treatment_embeddings.npy")
|
| 46 |
+
|
| 47 |
+
# Load chunks
|
| 48 |
+
with open(self.embeddings_dir / "emergency_chunks.json", 'r') as f:
|
| 49 |
+
self.emergency_chunks = json.load(f)
|
| 50 |
+
with open(self.embeddings_dir / "treatment_chunks.json", 'r') as f:
|
| 51 |
+
self.treatment_chunks = json.load(f)
|
| 52 |
+
|
| 53 |
+
# Initialize model
|
| 54 |
+
self.model = SentenceTransformer("NeuML/pubmedbert-base-embeddings")
|
| 55 |
+
|
| 56 |
+
self.logger.info("Test environment initialized successfully")
|
| 57 |
+
self.logger.info(f"Emergency embeddings shape: {self.emergency_emb.shape}")
|
| 58 |
+
self.logger.info(f"Treatment embeddings shape: {self.treatment_emb.shape}")
|
| 59 |
+
|
| 60 |
+
except FileNotFoundError as e:
|
| 61 |
+
self.logger.error(f"File not found: {e}")
|
| 62 |
+
raise
|
| 63 |
+
except Exception as e:
|
| 64 |
+
self.logger.error(f"Error during initialization: {e}")
|
| 65 |
+
raise
|
| 66 |
+
|
| 67 |
+
def _safe_search(
|
| 68 |
+
self,
|
| 69 |
+
index: AnnoyIndex,
|
| 70 |
+
query_vector: np.ndarray,
|
| 71 |
+
k: int = 5
|
| 72 |
+
) -> Tuple[Optional[List[int]], Optional[List[float]]]:
|
| 73 |
+
"""Safe search wrapper with error handling"""
|
| 74 |
+
try:
|
| 75 |
+
indices, distances = index.get_nns_by_vector(
|
| 76 |
+
query_vector, k, include_distances=True
|
| 77 |
+
)
|
| 78 |
+
self.logger.debug(f"Search successful: found {len(indices)} results")
|
| 79 |
+
return indices, distances
|
| 80 |
+
|
| 81 |
+
except Exception as e:
|
| 82 |
+
self.logger.error(f"Search failed: {str(e)}")
|
| 83 |
+
return None, None
|
| 84 |
+
|
| 85 |
+
def test_embedding_dimensions(self):
|
| 86 |
+
"""Test embedding dimensions and data quality."""
|
| 87 |
+
self.logger.info("\n=== Embedding Validation Report ===")
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
# Basic dimension checks
|
| 91 |
+
assert self.emergency_emb.shape[1] == 768, "Emergency embedding dimension should be 768"
|
| 92 |
+
assert self.treatment_emb.shape[1] == 768, "Treatment embedding dimension should be 768"
|
| 93 |
+
|
| 94 |
+
# Count verification
|
| 95 |
+
assert len(self.emergency_chunks) == self.emergency_emb.shape[0], \
|
| 96 |
+
"Emergency chunks count mismatch"
|
| 97 |
+
assert len(self.treatment_chunks) == self.treatment_emb.shape[0], \
|
| 98 |
+
"Treatment chunks count mismatch"
|
| 99 |
+
|
| 100 |
+
# Data quality checks
|
| 101 |
+
for name, emb in [("Emergency", self.emergency_emb),
|
| 102 |
+
("Treatment", self.treatment_emb)]:
|
| 103 |
+
# Check for NaN and Inf
|
| 104 |
+
assert not np.isnan(emb).any(), f"{name} contains NaN values"
|
| 105 |
+
assert not np.isinf(emb).any(), f"{name} contains Inf values"
|
| 106 |
+
|
| 107 |
+
# Value distribution analysis
|
| 108 |
+
self.logger.info(f"\n{name} Embeddings Statistics:")
|
| 109 |
+
self.logger.info(f"- Range: {np.min(emb):.3f} to {np.max(emb):.3f}")
|
| 110 |
+
self.logger.info(f"- Mean: {np.mean(emb):.3f}")
|
| 111 |
+
self.logger.info(f"- Std: {np.std(emb):.3f}")
|
| 112 |
+
|
| 113 |
+
self.logger.info("\n✅ All embedding validations passed")
|
| 114 |
+
|
| 115 |
+
except AssertionError as e:
|
| 116 |
+
self.logger.error(f"Validation failed: {str(e)}")
|
| 117 |
+
raise
|
| 118 |
+
|
| 119 |
+
def test_multiple_known_item_search(self):
|
| 120 |
+
"""Test ANNOY search with multiple random samples."""
|
| 121 |
+
self.logger.info("\n=== Multiple Known-Item Search Test ===")
|
| 122 |
+
|
| 123 |
+
emergency_index = AnnoyIndex(768, 'angular')
|
| 124 |
+
emergency_index.load(str(self.indices_dir / "emergency_index.ann"))
|
| 125 |
+
|
| 126 |
+
# Test 20 random samples
|
| 127 |
+
test_indices = np.random.choice(
|
| 128 |
+
self.emergency_emb.shape[0],
|
| 129 |
+
size=20,
|
| 130 |
+
replace=False
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
success_count = 0
|
| 134 |
+
for test_idx in test_indices:
|
| 135 |
+
try:
|
| 136 |
+
test_emb = self.emergency_emb[test_idx]
|
| 137 |
+
indices, distances = self._safe_search(emergency_index, test_emb)
|
| 138 |
+
|
| 139 |
+
if indices is None:
|
| 140 |
+
continue
|
| 141 |
+
|
| 142 |
+
# Verify self-retrieval
|
| 143 |
+
assert indices[0] == test_idx, f"Self-retrieval failed for index {test_idx}"
|
| 144 |
+
assert distances[0] < 0.0001, f"Self-distance too large for index {test_idx}"
|
| 145 |
+
success_count += 1
|
| 146 |
+
|
| 147 |
+
except AssertionError as e:
|
| 148 |
+
self.logger.warning(f"Test failed for index {test_idx}: {str(e)}")
|
| 149 |
+
|
| 150 |
+
self.logger.info(f"\n✅ {success_count}/20 self-retrieval tests passed")
|
| 151 |
+
assert success_count >= 18, "Less than 90% of self-retrieval tests passed"
|
| 152 |
+
|
| 153 |
+
def test_balanced_cross_dataset_search(self):
|
| 154 |
+
"""Test search across both emergency and treatment datasets."""
|
| 155 |
+
self.logger.info("\n=== Balanced Cross-Dataset Search Test ===")
|
| 156 |
+
|
| 157 |
+
# Initialize indices
|
| 158 |
+
emergency_index = AnnoyIndex(768, 'angular')
|
| 159 |
+
treatment_index = AnnoyIndex(768, 'angular')
|
| 160 |
+
|
| 161 |
+
try:
|
| 162 |
+
emergency_index.load(str(self.indices_dir / "emergency_index.ann"))
|
| 163 |
+
treatment_index.load(str(self.indices_dir / "treatment_index.ann"))
|
| 164 |
+
|
| 165 |
+
# Test queries
|
| 166 |
+
test_queries = [
|
| 167 |
+
"What is the treatment protocol for acute myocardial infarction?",
|
| 168 |
+
"How to manage severe chest pain with difficulty breathing?",
|
| 169 |
+
"What are the emergency procedures for anaphylactic shock?"
|
| 170 |
+
]
|
| 171 |
+
|
| 172 |
+
for query in test_queries:
|
| 173 |
+
print(f"\n\n=== Query: {query} ===")
|
| 174 |
+
|
| 175 |
+
# Generate query vector
|
| 176 |
+
query_emb = self.model.encode([query])[0]
|
| 177 |
+
|
| 178 |
+
# Get top-5 results from each dataset
|
| 179 |
+
e_indices, e_distances = self._safe_search(emergency_index, query_emb, k=5)
|
| 180 |
+
t_indices, t_distances = self._safe_search(treatment_index, query_emb, k=5)
|
| 181 |
+
|
| 182 |
+
if None in [e_indices, e_distances, t_indices, t_distances]:
|
| 183 |
+
self.logger.error("Search failed for one or both datasets")
|
| 184 |
+
continue
|
| 185 |
+
|
| 186 |
+
# Print first sentence of each result
|
| 187 |
+
print("\nEmergency Dataset Results:")
|
| 188 |
+
for i, (idx, dist) in enumerate(zip(e_indices, e_distances), 1):
|
| 189 |
+
text = self.emergency_chunks[idx]['text']
|
| 190 |
+
first_sentence = text.split('.')[0] + '.'
|
| 191 |
+
print(f"\nE-{i} (distance: {dist:.3f}):")
|
| 192 |
+
print(first_sentence)
|
| 193 |
+
|
| 194 |
+
print("\nTreatment Dataset Results:")
|
| 195 |
+
for i, (idx, dist) in enumerate(zip(t_indices, t_distances), 1):
|
| 196 |
+
text = self.treatment_chunks[idx]['text']
|
| 197 |
+
first_sentence = text.split('.')[0] + '.'
|
| 198 |
+
print(f"\nT-{i} (distance: {dist:.3f}):")
|
| 199 |
+
print(first_sentence)
|
| 200 |
+
|
| 201 |
+
except Exception as e:
|
| 202 |
+
self.logger.error(f"Test failed: {str(e)}")
|
| 203 |
+
raise
|
| 204 |
+
else:
|
| 205 |
+
self.logger.info("\n✅ Cross-dataset search test completed")
|
| 206 |
+
|
| 207 |
+
if __name__ == "__main__":
|
| 208 |
+
# Manual test execution
|
| 209 |
+
test = TestEmbeddingValidation()
|
| 210 |
+
test.setup_class()
|
| 211 |
+
test.test_embedding_dimensions()
|
| 212 |
+
test.test_multiple_known_item_search()
|
| 213 |
+
test.test_balanced_cross_dataset_search()
|