desinez commited on
Commit
1a72e1f
·
1 Parent(s): 9aecc8a

model packaging

Browse files
backend/PvDeepSetNet/src/DeepSets/Build_tensors.py CHANGED
@@ -3,7 +3,7 @@ import pandas as pd
3
  import json
4
  from collections import defaultdict
5
 
6
- def build_deepsets_tensors(df, M_max = 11, A_max = 5, purpose='prediction'):
7
  """
8
  df = dataframe
9
  M_max = the maximum number of unique marker within the dataset (default 11 <- used during training)
@@ -15,18 +15,13 @@ def build_deepsets_tensors(df, M_max = 11, A_max = 5, purpose='prediction'):
15
  required_cols = {'prior_C', 'prior_L', 'prior_I'}
16
  if not required_cols.issubset(df.columns):
17
  df['prior_C']=df['prior_L']=df['prior_I']=1/3
 
18
 
19
 
20
- # reading allele dictionary
21
  with open('allele_dict.json', 'r') as file:
22
  allele_to_id = json.load(file)
23
 
24
- # build tensor for target variable only if the purpose == evaluation
25
- y_given = False
26
- if purpose == 'evaluation':
27
- y_given=True
28
-
29
-
30
 
31
  # ----------------------------------------------------
32
  # 1. Encode categorical variables once
@@ -46,7 +41,6 @@ def build_deepsets_tensors(df, M_max = 11, A_max = 5, purpose='prediction'):
46
 
47
  priors = torch.zeros((N, 3))
48
  MOI = torch.zeros((N, 2))
49
- y = torch.zeros((N, 3))
50
 
51
  # ----------------------------------------------------
52
  # 3. Main loop (optimized)
@@ -58,8 +52,6 @@ def build_deepsets_tensors(df, M_max = 11, A_max = 5, purpose='prediction'):
58
  MOI2 = df_pair.loc[df_pair.episode == 2, 'MOI'].iloc[0]
59
 
60
  MOI[i] = torch.tensor([MOI1, MOI2])
61
- if y_given:
62
- y[i] = torch.tensor(df_pair[["post_C", "post_L", "post_I"]].iloc[0].values)
63
 
64
  # ---- pre-group alleles by (marker, episode)
65
  allele_dict = defaultdict(list)
@@ -79,12 +71,11 @@ def build_deepsets_tensors(df, M_max = 11, A_max = 5, purpose='prediction'):
79
  X_alleles[i, m_idx, e_idx, a_idx, 0] = allele_to_id[allele]
80
  X_alleles[i, m_idx, e_idx, a_idx, 1] = freq
81
  allele_mask[i, m_idx, e_idx, a_idx] = True
82
- final_tensors = {
83
- "X_alleles": X_alleles, "allele_mask": allele_mask,
84
- "marker_mask": marker_mask, "priors": priors,
85
- "MOI": MOI
86
- }
87
- if y_given:
88
- final_tensors['y'] = y
89
 
90
- return final_tensors
 
 
 
 
 
 
 
3
  import json
4
  from collections import defaultdict
5
 
6
+ def build_deepsets_tensors(df, M_max = 11, A_max = 5, purpose='prediction', prior='not_given'):
7
  """
8
  df = dataframe
9
  M_max = the maximum number of unique marker within the dataset (default 11 <- used during training)
 
15
  required_cols = {'prior_C', 'prior_L', 'prior_I'}
16
  if not required_cols.issubset(df.columns):
17
  df['prior_C']=df['prior_L']=df['prior_I']=1/3
18
+
19
 
20
 
21
+
22
  with open('allele_dict.json', 'r') as file:
23
  allele_to_id = json.load(file)
24
 
 
 
 
 
 
 
25
 
26
  # ----------------------------------------------------
27
  # 1. Encode categorical variables once
 
41
 
42
  priors = torch.zeros((N, 3))
43
  MOI = torch.zeros((N, 2))
 
44
 
45
  # ----------------------------------------------------
46
  # 3. Main loop (optimized)
 
52
  MOI2 = df_pair.loc[df_pair.episode == 2, 'MOI'].iloc[0]
53
 
54
  MOI[i] = torch.tensor([MOI1, MOI2])
 
 
55
 
56
  # ---- pre-group alleles by (marker, episode)
57
  allele_dict = defaultdict(list)
 
71
  X_alleles[i, m_idx, e_idx, a_idx, 0] = allele_to_id[allele]
72
  X_alleles[i, m_idx, e_idx, a_idx, 1] = freq
73
  allele_mask[i, m_idx, e_idx, a_idx] = True
 
 
 
 
 
 
 
74
 
75
+ return {
76
+ "X_alleles": X_alleles,
77
+ "allele_mask": allele_mask,
78
+ "marker_mask": marker_mask,
79
+ "priors": priors,
80
+ "MOI": MOI,
81
+ }
backend/PvDeepSetNet/src/DeepSets/DeepSets_pipeline.py CHANGED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import seaborn as sns
3
+ import matplotlib.pyplot as plt
4
+ from sklearn.metrics import r2_score
5
+ from DeepSets import DataPreprocessor, build_deepsets_tensors
6
+
7
+
8
+
9
+
10
+ def run_Prediction(data, mode='prediction'):
11
+
12
+ # perform basic preprocess
13
+ preprocessed_tensor = (
14
+ data
15
+ .pipe(DataPreprocessor.removing_single_episode_patients)
16
+ .pipe(DataPreprocessor.calculate_population_Allele_frequencies, population='country')
17
+ .pipe(DataPreprocessor.calculate_MOIs)
18
+ .pipe(DataPreprocessor.paired_episode_assigner)
19
+ .pipe(DataPreprocessor.build_deepsets_tensors, mode=mode)
20
+ )
21
+ loaded_data = DataPreprocessor.load_tensor(preprocessed_tensor, mode)
22
+ return loaded_data
23
+
24
+
backend/PvDeepSetNet/src/DeepSets/Preprocess.py CHANGED
@@ -1,6 +1,11 @@
1
  import pandas as pd
2
  import numpy as np
 
 
3
  from itertools import combinations
 
 
 
4
 
5
 
6
  class DataPreprocessor:
@@ -129,4 +134,116 @@ class DataPreprocessor:
129
 
130
  return df
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
 
1
  import pandas as pd
2
  import numpy as np
3
+ import torch
4
+ import json
5
  from itertools import combinations
6
+ from collections import defaultdict
7
+ from torch.utils.data import DataLoader, TensorDataset
8
+
9
 
10
 
11
  class DataPreprocessor:
 
134
 
135
  return df
136
 
137
+ @staticmethod
138
+ def build_deepsets_tensors(df, M_max=11, A_max=5, mode='prediction'):
139
+ """
140
+ df = dataframe
141
+ M_max = the maximum number of unique marker within the dataset (default 11 <- used during training)
142
+ A_max = the maximum number of unique allele per marker (default 5 <- used during training)
143
+ allele_to_id = alleles with their corresponding ids
144
+ Optimized Deep Sets preprocessing for Pv3Rs surrogate
145
+ """
146
+ # checking the existance of prior columns, otherwise the default values will be assigned
147
+ required_cols = {'prior_C', 'prior_L', 'prior_I'}
148
+ if not required_cols.issubset(df.columns):
149
+ df['prior_C']=df['prior_L']=df['prior_I']=1/3
150
+
151
+
152
+ # reading allele dictionary
153
+ with open('allele_dict.json', 'r') as file:
154
+ allele_to_id = json.load(file)
155
+
156
+ # build tensor for target variable only if the mode == evaluation
157
+ y_given = False
158
+ if mode == 'evaluation':
159
+ y_given=True
160
+
161
+ # ----------------------------------------------------
162
+ # 1. Encode categorical variables once
163
+ # ----------------------------------------------------
164
+ marker_to_id = {m: i + 1 for i, m in enumerate(df.marker.unique())}
165
+ allele_to_id = allele_to_id
166
+
167
+ grouped = list(df.groupby("sample_id_paired")) #computationally intensive
168
+ N = len(grouped)
169
+
170
+ # ----------------------------------------------------
171
+ # 2. Allocate tensors
172
+ # ----------------------------------------------------
173
+ X_alleles = torch.zeros((N, M_max, 2, A_max, 2))
174
+ allele_mask = torch.zeros((N, M_max, 2, A_max), dtype=torch.bool)
175
+ marker_mask = torch.zeros((N, M_max), dtype=torch.bool)
176
+
177
+ priors = torch.zeros((N, 3))
178
+ MOI = torch.zeros((N, 2))
179
+ y = torch.zeros((N, 3))
180
+
181
+ # ----------------------------------------------------
182
+ # 3. Main loop (optimized)
183
+ # ----------------------------------------------------
184
+ for i, (_, df_pair) in enumerate(grouped):
185
+ # ---- pair-level values (constant)
186
+ priors[i] = torch.tensor(df_pair[["prior_C", "prior_L", "prior_I"]].iloc[0].values)
187
+ MOI1 = df_pair.loc[df_pair.episode == 1, 'MOI'].iloc[0]
188
+ MOI2 = df_pair.loc[df_pair.episode == 2, 'MOI'].iloc[0]
189
+
190
+ MOI[i] = torch.tensor([MOI1, MOI2])
191
+ if y_given:
192
+ y[i] = torch.tensor(df_pair[["post_C", "post_L", "post_I"]].iloc[0].values)
193
+
194
+ # ---- pre-group alleles by (marker, episode)
195
+ allele_dict = defaultdict(list)
196
+ for row in df_pair.itertuples():
197
+ allele_dict[(row.marker, row.episode)].append((row.allele, row.frequency))
198
+
199
+ # ---- marker union
200
+ markers = sorted({m for (m, _) in allele_dict.keys()})[:M_max]
201
+
202
+ for m_idx, marker in enumerate(markers):
203
+ marker_mask[i, m_idx] = True
204
+
205
+ for e_idx, episode in enumerate([1, 2]):
206
+ alleles = allele_dict.get((marker, episode), [])
207
+
208
+ for a_idx, (allele, freq) in enumerate(alleles[:A_max]):
209
+ X_alleles[i, m_idx, e_idx, a_idx, 0] = allele_to_id[allele]
210
+ X_alleles[i, m_idx, e_idx, a_idx, 1] = freq
211
+ allele_mask[i, m_idx, e_idx, a_idx] = True
212
+ final_tensors = {
213
+ "X_alleles": X_alleles, "allele_mask": allele_mask,
214
+ "marker_mask": marker_mask, "priors": priors,
215
+ "MOI": MOI
216
+ }
217
+ if y_given:
218
+ final_tensors['y'] = y
219
+
220
+ return final_tensors
221
+ @staticmethod
222
+ def load_tensor(deepset_tensor, mode='prediction', batch_size=32):
223
+ """
224
+ Load tensors with specified batch size
225
+ """
226
+
227
+ # TensorDataset
228
+ if mode == 'prediction':
229
+ tensors = TensorDataset(
230
+ deepset_tensor["X_alleles"],
231
+ deepset_tensor["allele_mask"],
232
+ deepset_tensor["marker_mask"],
233
+ deepset_tensor["priors"],
234
+ deepset_tensor["MOI"]
235
+ )
236
+ elif mode == 'evaluation':
237
+ tensors = TensorDataset(
238
+ deepset_tensor["X_alleles"],
239
+ deepset_tensor["allele_mask"],
240
+ deepset_tensor["marker_mask"],
241
+ deepset_tensor["priors"],
242
+ deepset_tensor["MOI"],
243
+ deepset_tensor["y"]
244
+ )
245
+
246
+
247
+ return DataLoader(tensors, batch_size, shuffle=False)
248
+
249
 
backend/PvDeepSetNet/src/DeepSets/__init__.py CHANGED
@@ -1,2 +1,3 @@
1
  from .Build_tensors import build_deepsets_tensors
2
- from .Preprocess import DataPreprocessor
 
 
1
  from .Build_tensors import build_deepsets_tensors
2
+ from .Preprocess import DataPreprocessor
3
+ from .Model import PvDeepSets
backend/PvDeepSetNet/src/DeepSets/__pycache__/Build_tensors.cpython-310.pyc CHANGED
Binary files a/backend/PvDeepSetNet/src/DeepSets/__pycache__/Build_tensors.cpython-310.pyc and b/backend/PvDeepSetNet/src/DeepSets/__pycache__/Build_tensors.cpython-310.pyc differ
 
backend/PvDeepSetNet/src/DeepSets/__pycache__/Model.cpython-310.pyc ADDED
Binary file (2.07 kB). View file
 
backend/PvDeepSetNet/src/DeepSets/__pycache__/Preprocess.cpython-310.pyc CHANGED
Binary files a/backend/PvDeepSetNet/src/DeepSets/__pycache__/Preprocess.cpython-310.pyc and b/backend/PvDeepSetNet/src/DeepSets/__pycache__/Preprocess.cpython-310.pyc differ
 
backend/PvDeepSetNet/src/DeepSets/__pycache__/__init__.cpython-310.pyc CHANGED
Binary files a/backend/PvDeepSetNet/src/DeepSets/__pycache__/__init__.cpython-310.pyc and b/backend/PvDeepSetNet/src/DeepSets/__pycache__/__init__.cpython-310.pyc differ
 
backend/PvDeepSetNet/tests/temp.ipynb CHANGED
@@ -127,200 +127,48 @@
127
  },
128
  {
129
  "cell_type": "code",
130
- "execution_count": 2,
131
- "id": "5be7dab8",
132
- "metadata": {},
133
- "outputs": [],
134
- "source": [
135
- "from DeepSets import DataPreprocessor\n",
136
- "data_pre = (\n",
137
- " real_data\n",
138
- " .pipe(DataPreprocessor.removing_single_episode_patients)\n",
139
- " .pipe(DataPreprocessor.calculate_population_Allele_frequencies, population='country')\n",
140
- " .pipe(DataPreprocessor.calculate_MOIs)\n",
141
- " .pipe(DataPreprocessor.paired_episode_assigner)\n",
142
- ")"
143
- ]
144
- },
145
- {
146
- "cell_type": "code",
147
- "execution_count": null,
148
- "id": "41c16479",
149
- "metadata": {},
150
- "outputs": [],
151
- "source": []
152
- },
153
- {
154
- "cell_type": "code",
155
- "execution_count": 3,
156
- "id": "9cb4f6ad",
157
- "metadata": {},
158
- "outputs": [],
159
- "source": [
160
- "import DeepSets\n",
161
- "\n",
162
- "deepest_tensor =DeepSets.build_deepsets_tensors(data_pre)"
163
- ]
164
- },
165
- {
166
- "cell_type": "code",
167
- "execution_count": 6,
168
- "id": "cf9dea31",
169
  "metadata": {},
170
  "outputs": [
171
  {
172
- "data": {
173
- "text/plain": [
174
- "torch.Size([394, 11, 2, 5, 2])"
175
- ]
176
- },
177
- "execution_count": 6,
178
- "metadata": {},
179
- "output_type": "execute_result"
180
  }
181
  ],
182
  "source": [
183
- "deepest_tensor['X_alleles'].shape"
184
- ]
185
- },
186
- {
187
- "cell_type": "code",
188
- "execution_count": 8,
189
- "id": "afcf0fd7",
190
- "metadata": {},
191
- "outputs": [],
192
- "source": [
193
- "from torch.utils.data import DataLoader, TensorDataset\n",
194
- "\n",
195
- "# Option 1: TensorDataset\n",
196
- "test_dataset = TensorDataset(\n",
197
- " deepest_tensor[\"X_alleles\"],\n",
198
- " deepest_tensor[\"allele_mask\"],\n",
199
- " deepest_tensor[\"marker_mask\"],\n",
200
- " deepest_tensor[\"priors\"],\n",
201
- " deepest_tensor[\"MOI\"]\n",
202
- ")\n",
203
- "\n",
204
- "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
205
- ]
206
- },
207
- {
208
- "cell_type": "code",
209
- "execution_count": 9,
210
- "id": "dbed10c3",
211
- "metadata": {},
212
- "outputs": [],
213
- "source": [
214
- "import torch\n",
215
- "import torch.nn as nn\n",
216
- "import torch.nn.functional as F\n",
217
- "\n",
218
- "# =====================================================\n",
219
- "# Deep Sets model for Pv3Rs surrogate\n",
220
- "# =====================================================\n",
221
- "class PvDeepSets(nn.Module):\n",
222
- " def __init__(self,\n",
223
- " n_alleles, # total number of unique alleles\n",
224
- " allele_embed_dim=32,\n",
225
- " marker_embed_dim=64,\n",
226
- " pair_embed_dim=64,\n",
227
- " hidden_dim=64,\n",
228
- " n_classes=3):\n",
229
- " super(PvDeepSets, self).__init__()\n",
230
- "\n",
231
- " # -------------------------------------------------\n",
232
- " # 1️⃣ Allele embedding (allele ID + frequency)\n",
233
- " # -------------------------------------------------\n",
234
- " self.allele_embedding = nn.Embedding(n_alleles + 1, allele_embed_dim, padding_idx=0)\n",
235
- " self.allele_mlp = nn.Sequential(\n",
236
- " nn.Linear(allele_embed_dim + 1, allele_embed_dim), # +1 for frequency\n",
237
- " nn.ReLU(),\n",
238
- " nn.Linear(allele_embed_dim, allele_embed_dim),\n",
239
- " nn.ReLU()\n",
240
- " )\n",
241
- "\n",
242
- " # -------------------------------------------------\n",
243
- " # 2️⃣ Marker-level MLP (after comparing episodes)\n",
244
- " # -------------------------------------------------\n",
245
- " self.marker_mlp = nn.Sequential(\n",
246
- " nn.Linear(allele_embed_dim * 4, marker_embed_dim),\n",
247
- " nn.ReLU(),\n",
248
- " nn.Linear(marker_embed_dim, marker_embed_dim),\n",
249
- " nn.ReLU()\n",
250
- " )\n",
251
- "\n",
252
- " # -------------------------------------------------\n",
253
- " # 3️⃣ Pair-level MLP (aggregate markers + priors + MOI)\n",
254
- " # -------------------------------------------------\n",
255
- " self.pair_mlp = nn.Sequential(\n",
256
- " nn.Linear(marker_embed_dim + 3 + 2, pair_embed_dim), # +3 priors +2 MOI\n",
257
- " nn.ReLU(),\n",
258
- " nn.Linear(pair_embed_dim, hidden_dim),\n",
259
- " nn.ReLU(),\n",
260
- " nn.Linear(hidden_dim, n_classes)\n",
261
- " )\n",
262
- "\n",
263
- " def forward(self, X_alleles, allele_mask, marker_mask, priors, MOI):\n",
264
- " \"\"\"\n",
265
- " X_alleles : (batch, M_max, 2, A_max, 2)\n",
266
- " allele_mask: same shape as X_alleles[:,:,:,:,0]\n",
267
- " marker_mask: (batch, M_max)\n",
268
- " priors : (batch, 3)\n",
269
- " MOI : (batch, 2)\n",
270
- " \"\"\"\n",
271
- " B, M, E, A, _ = X_alleles.shape\n",
272
- "\n",
273
- " # ---------------------------------------------\n",
274
- " # 1️⃣ Embed alleles\n",
275
- " # ---------------------------------------------\n",
276
- " allele_ids = X_alleles[..., 0].long()\n",
277
- " freqs = X_alleles[..., 1]\n",
278
- "\n",
279
- " allele_emb = self.allele_embedding(allele_ids) # (B,M,E,A,allele_embed_dim)\n",
280
- " allele_input = torch.cat([allele_emb, freqs.unsqueeze(-1)], dim=-1)\n",
281
- " allele_out = self.allele_mlp(allele_input) # (B,M,E,A,allele_embed_dim)\n",
282
- "\n",
283
- " # Apply allele mask\n",
284
- " allele_out = allele_out * allele_mask.unsqueeze(-1)\n",
285
- "\n",
286
- " # ---------------------------------------------\n",
287
- " # 2️⃣ Aggregate alleles → marker embedding per episode\n",
288
- " # ---------------------------------------------\n",
289
- " # Sum pooling over alleles\n",
290
- " marker_ep_emb = allele_out.sum(dim=3) # (B,M,E,allele_embed_dim)\n",
291
- "\n",
292
- " # ---------------------------------------------\n",
293
- " # 3️⃣ Compare episodes (ep1 vs ep2)\n",
294
- " # ---------------------------------------------\n",
295
- " ep1 = marker_ep_emb[:, :, 0, :]\n",
296
- " ep2 = marker_ep_emb[:, :, 1, :]\n",
297
- "\n",
298
- " marker_pair = torch.cat([ep1, ep2, torch.abs(ep1 - ep2), ep1 * ep2], dim=-1) # (B,M,4*allele_embed_dim)\n",
299
- "\n",
300
- " # Apply marker-level MLP\n",
301
- " marker_emb = self.marker_mlp(marker_pair) # (B,M,marker_embed_dim)\n",
302
  "\n",
303
- " # Masked sum over markers\n",
304
- " marker_emb = marker_emb * marker_mask.unsqueeze(-1)\n",
305
- " pair_emb = marker_emb.sum(dim=1) # (B, marker_embed_dim)\n",
306
  "\n",
307
- " # ---------------------------------------------\n",
308
- " # 4️⃣ Concatenate priors + MOI\n",
309
- " # ---------------------------------------------\n",
310
- " pair_emb = torch.cat([pair_emb, priors, MOI], dim=-1) # (B, marker_dim+4)\n",
311
  "\n",
312
- " # ---------------------------------------------\n",
313
- " # 5️⃣ Pair-level MLP → logits\n",
314
- " # ---------------------------------------------\n",
315
- " logits = self.pair_mlp(pair_emb) # (B, n_classes)\n",
316
- " probs = F.softmax(logits, dim=-1)\n",
 
 
 
 
 
 
317
  "\n",
318
- " return probs\n"
319
  ]
320
  },
321
  {
322
  "cell_type": "code",
323
- "execution_count": 11,
324
  "id": "50b46ac3",
325
  "metadata": {},
326
  "outputs": [],
@@ -333,7 +181,7 @@
333
  },
334
  {
335
  "cell_type": "code",
336
- "execution_count": 12,
337
  "id": "7c5be94c",
338
  "metadata": {},
339
  "outputs": [
@@ -348,7 +196,7 @@
348
  "name": "stderr",
349
  "output_type": "stream",
350
  "text": [
351
- "C:\\Users\\sinel\\AppData\\Local\\Temp\\ipykernel_38672\\1365319441.py:11: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
352
  " model.load_state_dict(torch.load(\"../src/DeepSets/pv_deepsets_weights20260402.pth\", map_location=device))\n"
353
  ]
354
  },
@@ -358,12 +206,14 @@
358
  "<All keys matched successfully>"
359
  ]
360
  },
361
- "execution_count": 12,
362
  "metadata": {},
363
  "output_type": "execute_result"
364
  }
365
  ],
366
  "source": [
 
 
367
  "# 1. Define the device\n",
368
  "device = torch.device(\"cpu\")\n",
369
  "\n",
@@ -380,7 +230,7 @@
380
  },
381
  {
382
  "cell_type": "code",
383
- "execution_count": 14,
384
  "id": "581c0365",
385
  "metadata": {},
386
  "outputs": [
@@ -432,7 +282,7 @@
432
  " print(f\"Total undetermined samples removed: {undetermined_count}\")\n",
433
  " return np.vstack(all_predicted), y_pred_filtered\n",
434
  "\n",
435
- "predicted_probs, y_pred_hard = get_model_results(model, test_loader, device)\n",
436
  "\n",
437
  "\n"
438
  ]
 
127
  },
128
  {
129
  "cell_type": "code",
130
+ "execution_count": 7,
131
+ "id": "1ac9a6b0",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  "metadata": {},
133
  "outputs": [
134
  {
135
+ "name": "stdout",
136
+ "output_type": "stream",
137
+ "text": [
138
+ "11\n",
139
+ "394\n",
140
+ "5\n"
141
+ ]
 
142
  }
143
  ],
144
  "source": [
145
+ "import numpy as np\n",
146
+ "import seaborn as sns\n",
147
+ "import matplotlib.pyplot as plt\n",
148
+ "from sklearn.metrics import r2_score\n",
149
+ "from DeepSets import DataPreprocessor, build_deepsets_tensors\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  "\n",
 
 
 
151
  "\n",
152
+ "def run_Prediction(data, mode='prediction'):\n",
 
 
 
153
  "\n",
154
+ " # perform basic preprocess\n",
155
+ " preprocessed_tensor = (\n",
156
+ " data\n",
157
+ " .pipe(DataPreprocessor.removing_single_episode_patients)\n",
158
+ " .pipe(DataPreprocessor.calculate_population_Allele_frequencies, population='country')\n",
159
+ " .pipe(DataPreprocessor.calculate_MOIs)\n",
160
+ " .pipe(DataPreprocessor.paired_episode_assigner)\n",
161
+ " .pipe(DataPreprocessor.build_deepsets_tensors, mode=mode)\n",
162
+ " )\n",
163
+ " loaded_data = DataPreprocessor.load_tensor(preprocessed_tensor)\n",
164
+ " return loaded_data\n",
165
  "\n",
166
+ "result = run_Prediction(real_data)"
167
  ]
168
  },
169
  {
170
  "cell_type": "code",
171
+ "execution_count": 3,
172
  "id": "50b46ac3",
173
  "metadata": {},
174
  "outputs": [],
 
181
  },
182
  {
183
  "cell_type": "code",
184
+ "execution_count": 4,
185
  "id": "7c5be94c",
186
  "metadata": {},
187
  "outputs": [
 
196
  "name": "stderr",
197
  "output_type": "stream",
198
  "text": [
199
+ "C:\\Users\\sinel\\AppData\\Local\\Temp\\ipykernel_24916\\2347922982.py:13: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
200
  " model.load_state_dict(torch.load(\"../src/DeepSets/pv_deepsets_weights20260402.pth\", map_location=device))\n"
201
  ]
202
  },
 
206
  "<All keys matched successfully>"
207
  ]
208
  },
209
+ "execution_count": 4,
210
  "metadata": {},
211
  "output_type": "execute_result"
212
  }
213
  ],
214
  "source": [
215
+ "import torch\n",
216
+ "from DeepSets import PvDeepSets\n",
217
  "# 1. Define the device\n",
218
  "device = torch.device(\"cpu\")\n",
219
  "\n",
 
230
  },
231
  {
232
  "cell_type": "code",
233
+ "execution_count": 5,
234
  "id": "581c0365",
235
  "metadata": {},
236
  "outputs": [
 
282
  " print(f\"Total undetermined samples removed: {undetermined_count}\")\n",
283
  " return np.vstack(all_predicted), y_pred_filtered\n",
284
  "\n",
285
+ "predicted_probs, y_pred_hard = get_model_results(model, result, device)\n",
286
  "\n",
287
  "\n"
288
  ]