a b/exp_template-mv-nn-v3.ipynb
1
{
2
 "cells": [
3
  {
4
   "cell_type": "code",
5
   "execution_count": null,
6
   "metadata": {},
7
   "outputs": [],
8
   "source": [
9
    "import socket\n",
10
    "if socket.gethostname() == 'dlm':\n",
11
    "  %env CUDA_DEVICE_ORDER=PCI_BUS_ID\n",
12
    "  %env CUDA_VISIBLE_DEVICES=3"
13
   ]
14
  },
15
  {
16
   "cell_type": "code",
17
   "execution_count": 1,
18
   "metadata": {},
19
   "outputs": [
20
    {
21
     "name": "stdout",
22
     "output_type": "stream",
23
     "text": [
24
      "Using CPU:(\n"
25
     ]
26
    }
27
   ],
28
   "source": [
29
    "import os\n",
30
    "import sys\n",
31
    "import re\n",
32
    "import collections\n",
33
    "import functools\n",
34
    "import itertools\n",
35
    "import requests, zipfile, io\n",
36
    "import pickle\n",
37
    "import copy\n",
38
    "\n",
39
    "import pandas\n",
40
    "import numpy as np\n",
41
    "import matplotlib\n",
42
    "import matplotlib.pyplot as plt\n",
43
    "import sklearn\n",
44
    "import sklearn.decomposition\n",
45
    "import sklearn.metrics\n",
46
    "import networkx\n",
47
    "\n",
48
    "import torch\n",
49
    "import torch.nn as nn\n",
50
    "\n",
51
    "lib_path = 'I:/code'\n",
52
    "if not os.path.exists(lib_path):\n",
53
    "  lib_path = '/media/6T/.tianle/.lib'\n",
54
    "if not os.path.exists(lib_path):\n",
55
    "  lib_path = '/projects/academic/azhang/tianlema/lib'\n",
56
    "if os.path.exists(lib_path) and lib_path not in sys.path:\n",
57
    "  sys.path.append(lib_path)\n",
58
    "  \n",
59
    "from dl.models.basic_models import *\n",
60
    "from dl.utils.visualization.visualization import *\n",
61
    "from dl.utils.outlier import *\n",
62
    "from dl.utils.train import *\n",
63
    "from autoencoder.autoencoder import *\n",
64
    "from vin.vin import *\n",
65
    "from dl.utils.utils import get_overlap_samples, filter_clinical_dict, get_target_variable\n",
66
    "from dl.utils.utils import get_shuffled_data, target_to_numpy, discrete_to_id, get_mi_acc\n",
67
    "from dl.utils.utils import get_label_distribution, normalize_continuous_variable\n",
68
    "\n",
69
    "%load_ext autoreload\n",
70
    "%autoreload 2\n",
71
    "\n",
72
    "\n",
73
    "use_gpu = True\n",
74
    "if use_gpu and torch.cuda.is_available():\n",
75
    "  device = torch.device('cuda')\n",
76
    "  print('Using GPU:)')\n",
77
    "else:\n",
78
    "  device = torch.device('cpu')\n",
79
    "  print('Using CPU:(')"
80
   ]
81
  },
82
  {
83
   "cell_type": "code",
84
   "execution_count": 2,
85
   "metadata": {},
86
   "outputs": [],
87
   "source": [
88
    "# neural net models include nn (mlp), resnet, densenet; another choice is ml (machine learning)\n",
89
    "# model_type, dense, residual are dependent\n",
90
    "model_type = 'resnet'\n",
91
    "dense = False\n",
92
    "residual = True\n",
93
    "hidden_dim = [100, 100]\n",
94
    "train_portion = 0.7\n",
95
    "val_portion = 0.1\n",
96
    "test_portion = 0.2\n",
97
    "num_train_types = -1 # -1 means not used\n",
98
    "num_val_types = -1\n",
99
    "num_test_types = -1 # this will almost never be used \n",
100
    "num_sets = 10\n",
101
    "num_folds = 10 # no longer used anymore\n",
102
    "sel_set_idx = 0\n",
103
    "cv_type = 'instance-shuffle' # or 'group-shuffle'; cross validation shuffle method\n",
104
    "sel_disease_types = 'all'\n",
105
    "# The number of total samples and the numbers for each class in selected disease types must >=\n",
106
    "min_num_samples_per_type_cls = [100, 0]\n",
107
    "# if 'auto-search', will search for the file first; if not exist, then generate random data split\n",
108
    "# and write to the file;\n",
109
    "# if string other than 'auto-search' is provided, assume the string is a proper file name, \n",
110
    "# and read the file;\n",
111
    "# if False, will generate a random data split, but not write to file \n",
112
    "# if True will generate a random data split, and write to file\n",
113
    "predefined_sample_set_file = 'auto-search' \n",
114
    "target_variable = ['PFI', 'DFI', 'PFI.time'] # To do: target variable can be a list (partially handled)\n",
115
    "target_variable_type = ['discrete', 'discrete', 'continuous'] # or 'continuous' real numbers\n",
116
    "target_variable_range = [[0,1],[0,1],[0,float('Inf')]]\n",
117
    "data_type = ['gene', 'methy', 'rppa', 'mirna']\n",
118
    "normal_transform_feature = True\n",
119
    "additional_vars = ['age_at_initial_pathologic_diagnosis', 'gender', 'ajcc_pathologic_tumor_stage']\n",
120
    "additional_var_types = ['continuous', 'discrete', 'discrete']\n",
121
    "additional_var_ranges = [[0, 100], ['MALE', 'FEMALE'], \n",
122
    "                         ['I/II NOS', 'IS', 'Stage 0', 'Stage I', 'Stage IA', 'Stage IB', \n",
123
    "                          'Stage II', 'Stage IIA', 'Stage IIB', 'Stage IIC', 'Stage III',\n",
124
    "                          'Stage IIIA', 'Stage IIIB', 'Stage IIIC', 'Stage IV', 'Stage IVA',\n",
125
    "                          'Stage IVB', 'Stage IVC', 'Stage X']]\n",
126
    "randomize_labels = False\n",
127
    "lr = 5e-4\n",
128
    "weight_decay = 1e-4\n",
129
    "num_epochs = 100\n",
130
    "reduce_every = 500\n",
131
    "show_results_in_notebook = True"
132
   ]
133
  },
134
  {
135
   "cell_type": "markdown",
136
   "metadata": {},
137
   "source": [
138
    "## Prepare data"
139
   ]
140
  },
141
  {
142
   "cell_type": "code",
143
   "execution_count": 3,
144
   "metadata": {},
145
   "outputs": [
146
    {
147
     "name": "stdout",
148
     "output_type": "stream",
149
     "text": [
150
      "feature_mat: rppa, max=14.141, min=-7.869, mean=0.095, 0.516\n",
151
      "feature_mat: mirna, max=11.813, min=0.000, mean=3.743, 1.000\n",
152
      "feature_mat: gene, max=16.311, min=0.000, mean=8.412, 1.000\n",
153
      "feature_mat: methy, max=1.000, min=0.000, mean=0.553, 1.000\n",
154
      "feature_interaction_mat: rppa, max=1.000, min=0.000, mean=0.198, 0.277\n",
155
      "feature_interaction_mat: mirna, max=1.000, min=0.010, mean=0.492, 1.000\n",
156
      "feature_interaction_mat: gene, max=1.000, min=0.000, mean=0.050, 0.146\n",
157
      "feature_interaction_mat: methy, max=1.000, min=0.000, mean=0.057, 0.127\n",
158
      "rppa (189,) X1433EPSILON\n",
159
      "mirna (662,) hsa-let-7a-2-3p\n",
160
      "gene (4942,) A1BG\n",
161
      "methy (4753,) cg00005847\n",
162
      "rppa (7480,) TCGA-OR-A5J2-01A-21-A39K-20\n",
163
      "mirna (9554,) TCGA-C4-A0F6-01A-11R-A10V-13\n",
164
      "gene (9702,) TCGA-OR-A5J1-01A-11R-A29S-07\n",
165
      "methy (10268,) TCGA-02-0001-01C-01D-0186-05\n"
166
     ]
167
    }
168
   ],
169
   "source": [
170
    "result_folder = 'results'\n",
171
    "data_split_idx_folder = f'{result_folder}/data_split_idx'\n",
172
    "project_folder = '../../pan-can-atlas' # on dlm or ccr\n",
173
    "print_stats = True\n",
174
    "if not os.path.exists(project_folder):\n",
175
    "  project_folder = 'F:/TCGA/Pan-Cancer-Atlas' # on my own desktop\n",
176
    "filepath = f'{project_folder}/data/processed/combined2.pkl'\n",
177
    "with open(filepath, 'rb') as f:\n",
178
    "  data = pickle.load(f)\n",
179
    "  patient_clinical = data['patient_clinical']\n",
180
    "  feature_mat_dict = data['feature_mat_dict']\n",
181
    "  feature_interaction_mat_dict = data['feature_interaction_mat_dict']\n",
182
    "  feature_id_dict = data['feature_id_dict']\n",
183
    "  aliquot_id_dict = data['aliquot_id_dict']\n",
184
    "#   sel_patient_ids = data['sample_id_sel']\n",
185
    "#   sample_idx_sel_dict = data['sample_idx_sel_dict']\n",
186
    "#   for k, v in sample_idx_sel_dict.items():\n",
187
    "#     assert [i[:12] for i in aliquot_id_dict[k][v]] == sel_patient_ids\n",
188
    "\n",
189
    "if print_stats:\n",
190
    "  for k, v in feature_mat_dict.items():\n",
191
    "    print(f'feature_mat: {k}, max={v.max():.3f}, min={v.min():.3f}, '\n",
192
    "          f'mean={v.mean():.3f}, {np.mean(v>0):.3f}')  \n",
193
    "  for k, v in feature_interaction_mat_dict.items():\n",
194
    "    print(f'feature_interaction_mat: {k}, max={v.max():.3f}, min={v.min():.3f}, '\n",
195
    "          f'mean={v.mean():.3f}, {np.mean(v>0):.3f}') \n",
196
    "  for k, v in feature_id_dict.items():\n",
197
    "    print(k, v.shape, v[0])\n",
198
    "  for k, v in aliquot_id_dict.items():\n",
199
    "    print(k, v.shape, v[0])"
200
   ]
201
  },
202
  {
203
   "cell_type": "code",
204
   "execution_count": 4,
205
   "metadata": {},
206
   "outputs": [
207
    {
208
     "name": "stdout",
209
     "output_type": "stream",
210
     "text": [
211
      "THCA {0.0: 240, 1.0: 24}\n",
212
      "BLCA {0.0: 125, 1.0: 25}\n",
213
      "BRCA {0.0: 666, 1.0: 62}\n",
214
      "KIRP {0.0: 101, 1.0: 22}\n",
215
      "STAD {1.0: 37, 0.0: 149}\n",
216
      "LIHC {0.0: 62, 1.0: 68}\n",
217
      "LUAD {1.0: 56, 0.0: 129}\n",
218
      "COAD {0.0: 108, 1.0: 17}\n",
219
      "LUSC {0.0: 136, 1.0: 56}\n",
220
      "Selected 2083 patients from 9 disease_types\n"
221
     ]
222
    }
223
   ],
224
   "source": [
225
    "# select samples with required clinical variables\n",
226
    "clinical_dict = filter_clinical_dict(target_variable, target_variable_type=target_variable_type, \n",
227
    "                                     target_variable_range=target_variable_range, \n",
228
    "                                     clinical_dict=patient_clinical)\n",
229
    "if len(additional_vars) > 0:\n",
230
    "  clinical_dict = filter_clinical_dict(additional_vars, target_variable_type=additional_var_types, \n",
231
    "                                       target_variable_range=additional_var_ranges, \n",
232
    "                                       clinical_dict=clinical_dict)\n",
233
    "\n",
234
    "# select samples with feature matrix of given type(s)\n",
235
    "if isinstance(data_type, str):\n",
236
    "  sample_list = {s[:12] for s in aliquot_id_dict[data_type]}\n",
237
    "  data_type_str = data_type\n",
238
    "elif isinstance(data_type, (list, tuple)):\n",
239
    "  sample_list = get_overlap_samples([aliquot_id_dict[dtype] for dtype in data_type], \n",
240
    "                                    common_list=None, start=0, end=12, return_common_list=True)\n",
241
    "  data_type_str = '-'.join(sorted(data_type))\n",
242
    "else:\n",
243
    "  raise ValueError(f'data_type must be str or list/tuple, but is {type(data_type)}')\n",
244
    "sample_list = set(sample_list).intersection(clinical_dict)\n",
245
    "\n",
246
    "# select samples with given disease types\n",
247
    "sel_disease_type_str = sel_disease_types # will be overwritten if it is a list\n",
248
    "if isinstance(sel_disease_types, (list, tuple)):\n",
249
    "  sample_list = [s for s in sample_list if clinical_dict[s]['type'] in sel_disease_types]\n",
250
    "  sel_disease_type_str = '-'.join(sorted(sel_disease_types))\n",
251
    "elif isinstance(sel_disease_types, str) and sel_disease_types!='all':\n",
252
    "  sample_list = [s for s in sample_list if clinical_dict[s]['type'] == sel_disease_types]\n",
253
    "else:\n",
254
    "  assert sel_disease_types == 'all'\n",
255
    " \n",
256
    "# For classification tasks with given min_num_samples_per_type_cls,\n",
257
    "# only keep disease types that have a minimal number of samples per type and per class\n",
258
    "# Reflection: it might be better to use collections.defaultdict(list) to store samples in each type\n",
259
    "type_cnt = collections.Counter([clinical_dict[s]['type'] for s in sample_list])\n",
260
    "if sum(min_num_samples_per_type_cls)>0 and (target_variable_type=='discrete' \n",
261
    "                                            or target_variable_type[0]=='discrete'):\n",
262
    "  # the number of samples in each disease type >= min_num_samples_per_type_cls[0]\n",
263
    "  type_cnt = {k: v for k, v in type_cnt.items() if v >= min_num_samples_per_type_cls[0]}\n",
264
    "  disease_type_cnt = {}\n",
265
    "  for k in type_cnt:\n",
266
    "    # collections.Counter can accept generator\n",
267
    "    cls_cnt = collections.Counter(clinical_dict[s][target_variable] \n",
268
    "                                  if isinstance(target_variable, str) \n",
269
    "                                  else clinical_dict[s][target_variable[0]] \n",
270
    "                                  for s in sample_list if clinical_dict[s]['type']==k)\n",
271
    "    if all([v >= min_num_samples_per_type_cls[1] for v in cls_cnt.values()]):\n",
272
    "      # the number of samples in each class >= min_num_samples_per_type_cls[1]\n",
273
    "      disease_type_cnt[k] = dict(cls_cnt)\n",
274
    "      print(k, disease_type_cnt[k])\n",
275
    "  sample_list = [s for s in sample_list if clinical_dict[s]['type'] in disease_type_cnt]\n",
276
    "sel_patient_ids = sorted(sample_list)\n",
277
    "print(f'Selected {len(sel_patient_ids)} patients from {len(disease_type_cnt)} disease_types')"
278
   ]
279
  },
280
  {
281
   "cell_type": "markdown",
282
   "metadata": {},
283
   "source": [
284
    "### Split data into training, validation, and test sets"
285
   ]
286
  },
287
  {
288
   "cell_type": "code",
289
   "execution_count": 5,
290
   "metadata": {},
291
   "outputs": [
292
    {
293
     "name": "stdout",
294
     "output_type": "stream",
295
     "text": [
296
      "Read predefined_sample_set_file: results/data_split_idx/PFI-DFI-PFI.time_instance-shuffle_age_at_initial_pathologic_diagnosis-ajcc_pathologic_tumor_stage-gender_gene-methy-mirna-rppa_all_100-0_0.7-0.1-0.2_10sets.pkl\n"
297
     ]
298
    }
299
   ],
300
   "source": [
301
    "predefined_sample_set_filename = (target_variable if isinstance(target_variable,str) \n",
302
    "                                else '-'.join(target_variable))\n",
303
    "predefined_sample_set_filename += f'_{cv_type}'\n",
304
    "if len(additional_vars) > 0:\n",
305
    "  predefined_sample_set_filename += f\"_{'-'.join(sorted(additional_vars))}\"\n",
306
    "\n",
307
    "predefined_sample_set_filename += (f\"_{data_type_str}_{sel_disease_type_str}_\"\n",
308
    "                                   f\"{'-'.join(map(str, min_num_samples_per_type_cls))}\")\n",
309
    "predefined_sample_set_filename += f\"_{'-'.join(map(str, [train_portion, val_portion, test_portion]))}\"\n",
310
    "if cv_type == 'group-shuffle' and num_train_types > 0:\n",
311
    "  predefined_sample_set_filename += f\"_{'-'.join(map(str, [num_train_types, num_val_types, num_test_types]))}\"\n",
312
    "predefined_sample_set_filename += f'_{num_sets}sets'\n",
313
    "res_file = f\"{predefined_sample_set_filename}_{sel_set_idx}_{'-'.join(map(str, hidden_dim))}_{model_type}.pkl\"\n",
314
    "predefined_sample_set_filename += '.pkl'\n",
315
    "# This will be overwritten if predefined_sample_set_file == 'auto-search' or filepath, and the file exists\n",
316
    "predefined_sample_sets = [get_shuffled_data(sel_patient_ids, clinical_dict, cv_type=cv_type, \n",
317
    "                  instance_portions=[train_portion, val_portion, test_portion], \n",
318
    "                  group_sizes=[num_train_types, num_val_types, num_test_types],\n",
319
    "                  group_variable_name='type', seed=None, verbose=False) for i in range(num_sets)]\n",
320
    "if predefined_sample_set_file == 'auto-search':\n",
321
    "  if os.path.exists(f'{data_split_idx_folder}/{predefined_sample_set_filename}'):\n",
322
    "    with open(f'{data_split_idx_folder}/{predefined_sample_set_filename}', 'rb') as f:\n",
323
    "      print(f'Read predefined_sample_set_file: '\n",
324
    "            f'{data_split_idx_folder}/{predefined_sample_set_filename}')\n",
325
    "      tmp = pickle.load(f)\n",
326
    "      # overwrite calculated predefined_sample_sets\n",
327
    "      predefined_sample_sets = tmp['predefined_sample_sets']    \n",
328
    "elif isinstance(predefined_sample_set_file, str): # but not 'auto-search'; assume it's a file name\n",
329
    "  if os.path.exists(predefined_sample_set_file):\n",
330
    "    with open(f'{data_split_idx_folder}/{predefined_sample_set_file}', 'rb') as f:\n",
331
    "      print(f'Read predefined_sample_set_file: {data_split_idx_folder}/{predefined_sample_set_file}')\n",
332
    "      tmp = pickle.load(f)\n",
333
    "      predefined_sample_sets = tmp['predefined_sample_sets']\n",
334
    "  else:\n",
335
    "    raise ValueError(f'predefined_sample_set_file: {data_split_idx_folder}/{predefined_sample_set_file} does not exist!')\n",
336
    "\n",
337
    "if (not os.path.exists(f'{data_split_idx_folder}/{predefined_sample_set_filename}') \n",
338
    "    and predefined_sample_set_file == 'auto-search') or predefined_sample_set_file is True:\n",
339
    "  with open(f'{data_split_idx_folder}/{predefined_sample_set_filename}', 'wb') as f:\n",
340
    "      print(f'Write predefined_sample_set_file: {data_split_idx_folder}/{predefined_sample_set_filename}')\n",
341
    "      pickle.dump({'predefined_sample_sets': predefined_sample_sets}, f)\n",
342
    "     \n",
343
    "sel_patient_ids, idx_splits = predefined_sample_sets[sel_set_idx]\n",
344
    "train_idx, val_idx, test_idx = idx_splits"
345
   ]
346
  },
347
  {
348
   "cell_type": "code",
349
   "execution_count": 6,
350
   "metadata": {},
351
   "outputs": [],
352
   "source": [
353
    "if isinstance(data_type, str):\n",
354
    "  sample_lists = [aliquot_id_dict[data_type]]\n",
355
    "else:\n",
356
    "  assert isinstance(data_type, (list, tuple))\n",
357
    "  sample_lists = [aliquot_id_dict[dtype] for dtype in data_type]\n",
358
    "idx_lists = get_overlap_samples(sample_lists=sample_lists, common_list=sel_patient_ids, \n",
359
    "                    start=0, end=12, return_common_list=False)\n",
360
    "sample_idx_sel_dict = {}\n",
361
    "if isinstance(data_type, str):\n",
362
    "  sample_idx_sel_dict = {data_type: idx_lists[0]}\n",
363
    "else:\n",
364
    "  sample_idx_sel_dict = {dtype: idx_list for dtype, idx_list in zip(data_type, idx_lists)}"
365
   ]
366
  },
367
  {
368
   "cell_type": "code",
369
   "execution_count": 7,
370
   "metadata": {},
371
   "outputs": [
372
    {
373
     "name": "stdout",
374
     "output_type": "stream",
375
     "text": [
376
      "gene: (2083, 4942); interaction_mat: mean=0.000057, std=0.000194, 4942\n",
377
      "methy: (2083, 4753); interaction_mat: mean=0.000069, std=0.000199, 4753\n",
378
      "rppa: (2083, 189); interaction_mat: mean=0.002668, std=0.004569, 189\n",
379
      "mirna: (2083, 662); interaction_mat: mean=0.001408, std=0.000547, 662\n"
380
     ]
381
    }
382
   ],
383
   "source": [
384
    "if isinstance(data_type, str):\n",
385
    "  print(f'Only use one data type: {data_type}')\n",
386
    "  num_data_types = 1\n",
387
    "  mat = feature_mat_dict[data_type][sample_idx_sel_dict[data_type]]\n",
388
    "  # Data preprocessing: make each row have mean 0 and sd 1.\n",
389
    "  x = (mat - mat.mean(axis=1, keepdims=True)) / mat.std(axis=1, keepdims=True)\n",
390
    "  interaction_mat = feature_interaction_mat_dict[data_type]\n",
391
    "  interaction_mat = torch.from_numpy(interaction_mat).float().to(device)\n",
392
    "  # Normalize these interaction mat\n",
393
    "  interaction_mat = interaction_mat / interaction_mat.norm()\n",
394
    "else:\n",
395
    "  mat = []\n",
396
    "  interaction_mats = []\n",
397
    "  in_dims = []\n",
398
    "  num_data_types = len(data_type)\n",
399
    "  # do not handle the special case of [data_type] to avoid too much code complexity\n",
400
    "  assert num_data_types > 1 \n",
401
    "  for dtype in data_type: # multiple data types\n",
402
    "    m = feature_mat_dict[dtype][sample_idx_sel_dict[dtype]]\n",
403
    "    #When there are multiple data types, make sure each type is normalized to have mean 0 and std 1\n",
404
    "    m = (m - m.mean(axis=1, keepdims=True)) / m.std(axis=1, keepdims=True)\n",
405
    "    mat.append(m)\n",
406
    "    in_dims.append(m.shape[1])\n",
407
    "    # For neural network model graph laplacian regularizer\n",
408
    "    interaction_mat = feature_interaction_mat_dict[dtype]\n",
409
    "    interaction_mat = torch.from_numpy(interaction_mat).float().to(device)\n",
410
    "    # Normalize these interaction mat\n",
411
    "    interaction_mat = interaction_mat / interaction_mat.norm()\n",
412
    "    interaction_mats.append(interaction_mat)\n",
413
    "    print(f'{dtype}: {m.shape}; '\n",
414
    "          f'interaction_mat: mean={interaction_mat.mean().item():2f}, '\n",
415
    "          f'std={interaction_mat.std().item():2f}, {interaction_mat.shape[0]}')\n",
416
    "  # Later interaction_mat will be passed to Loss_feature_interaction\n",
417
    "  interaction_mat = interaction_mats\n",
418
    "  mat = np.concatenate(mat, axis=1)\n",
419
    "  # For machine learing methods that use concatenated features without knowing underlying views,\n",
420
    "  # it might be good to make each row have mean 0 and sd 1.\n",
421
    "  x = (mat - mat.mean(axis=1, keepdims=True)) / mat.std(axis=1, keepdims=True)\n",
422
    "\n",
423
    "if normal_transform_feature:\n",
424
    "  X = x\n",
425
    "else:\n",
426
    "  X = mat"
427
   ]
428
  },
429
  {
430
   "cell_type": "code",
431
   "execution_count": 8,
432
   "metadata": {},
433
   "outputs": [
434
    {
435
     "name": "stdout",
436
     "output_type": "stream",
437
     "text": [
438
      "torch.Size([1458, 10546]) torch.Size([208, 10546]) torch.Size([417, 10546])\n"
439
     ]
440
    }
441
   ],
442
   "source": [
443
    "# sklearn classifiers also accept torch.Tensor\n",
444
    "X = torch.tensor(X).float().to(device)\n",
445
    "x_train = X[train_idx]\n",
446
    "x_val = X[val_idx]\n",
447
    "x_test = X[test_idx]\n",
448
    "print(x_train.shape, x_val.shape, x_test.shape)"
449
   ]
450
  },
451
  {
452
   "cell_type": "code",
453
   "execution_count": 12,
454
   "metadata": {},
455
   "outputs": [
456
    {
457
     "name": "stdout",
458
     "output_type": "stream",
459
     "text": [
460
      "Changed class labels for the model: {0.0: 0, 1.0: 1}\n",
461
      "Changed class labels for the model: {0.0: 0, 1.0: 1}\n",
462
      "PFI:\n",
463
      "train:torch.Size([1458]), val:torch.Size([208]), test:torch.Size([417])\n",
464
      "label distribution:\n",
465
      " [[0.82304525 0.84615386 0.81534773]\n",
466
      " [0.17695473 0.15384616 0.18465228]]\n",
467
      "DFI:\n",
468
      "train:torch.Size([1458]), val:torch.Size([208]), test:torch.Size([417])\n",
469
      "label distribution:\n",
470
      " [[0.8360768  0.84615386 0.82254195]\n",
471
      " [0.16392319 0.15384616 0.17745803]]\n",
472
      "PFI.time:\n",
473
      "train:torch.Size([1458, 1]), val:torch.Size([208, 1]), test:torch.Size([417, 1])\n"
474
     ]
475
    }
476
   ],
477
   "source": [
478
    "y_targets = get_target_variable(target_variable, clinical_dict, sel_patient_ids)\n",
479
    "y_targets = normalize_continuous_variable(y_targets, target_variable_type, transform=True, \n",
480
    "                                          forced=False, threshold=10, rm_outlier=True, whis=1.5, \n",
481
    "                                          only_positive=True, max_val=1)\n",
482
    "y_true = target_to_numpy(y_targets, target_variable_type, target_variable_range)\n",
483
    "if len(additional_vars) > 0:\n",
484
    "  additional_variables = get_target_variable(additional_vars, clinical_dict, sel_patient_ids)\n",
485
    "  # to do handle additional variables such as age and gender\n",
486
    "\n",
487
    "# should have written a recursive function instead\n",
488
    "if isinstance(target_variable_type, list):\n",
489
    "  y_targets = []\n",
490
    "  num_cls = []\n",
491
    "  y_train = []\n",
492
    "  y_val = []\n",
493
    "  y_test = []\n",
494
    "  for i, var_type in enumerate(target_variable_type):\n",
495
    "    y = torch.tensor(y_true[i]).to(device)\n",
496
    "    if var_type == 'discrete':\n",
497
    "      y = y.long()\n",
498
    "    elif var_type == 'continuous':\n",
499
    "      y = y.float()\n",
500
    "      if y.dim()==1:\n",
501
    "        y = y.unsqueeze(-1)\n",
502
    "    else:\n",
503
    "      raise ValueError(f'target type should be either discrete or continuous but is {var_type}')\n",
504
    "    y_targets.append(y)\n",
505
    "    num_cls.append(len(torch.unique(y))) # include continous target variables\n",
506
    "    y_train.append(y[train_idx])\n",
507
    "    y_val.append(y[val_idx])\n",
508
    "    y_test.append(y[test_idx])\n",
509
    "    print(f'{target_variable[i]}:\\ntrain:{y_train[-1].shape}, val:{y_val[-1].shape}, '\n",
510
    "         f'test:{y_test[-1].shape}')\n",
511
    "    if var_type == 'discrete':\n",
512
    "      label_probs = get_label_distribution([y_train[-1], y_val[-1], y_test[-1]])\n",
513
    "      if randomize_labels: # Optionally randomize true class labels\n",
514
    "        print('Randomize class labels!')\n",
515
    "        y_train[-1] = torch.multinomial(label_probs[0], len(y_train[-1]), replacement=True)\n",
516
    "        if len(y_val) > 0:\n",
517
    "          y_val[-1] = torch.multinomial(label_probs[1], len(y_val[-1]), replacement=True)\n",
518
    "        if len(y_test) > 0:\n",
519
    "          y_test[-1] = torch.multinomial(label_probs[2], len(y_test[-1]), replacement=True)\n",
520
    "        get_label_distribution([y_train[-1], y_val[-1], y_test[-1]])\n",
521
    "  y_true = y_targets\n",
522
    "elif isinstance(target_variable_type, str):\n",
523
    "  y = torch.tensor(y_true).to(device)\n",
524
    "  if var_type == 'discrete':\n",
525
    "    y = y.long()\n",
526
    "  elif var_type == 'continuous':\n",
527
    "    y = y.float()\n",
528
    "    if y.dim()==1:\n",
529
    "      y = y.unsqueeze(-1)\n",
530
    "  else:\n",
531
    "    raise ValueError(f'target type should be either discrete or continuous but is {var_type}')\n",
532
    "  y_true = y\n",
533
    "  num_cls = len(torch.unique(y_true))\n",
534
    "  y_train = y_true[train_idx]\n",
535
    "  y_val = y_true[val_idx]\n",
536
    "  y_test = y_true[test_idx]\n",
537
    "  print(f'{target_variable}:\\ntrain:{y_train.shape}, val:{y_val.shape}, '\n",
538
    "         f'test:{y_test.shape}')\n",
539
    "  label_probs = get_label_distribution([y_train, y_val, y_test])\n",
540
    "  if randomize_labels: # Optionally randomize true class labels\n",
541
    "    print('Randomize class labels!')\n",
542
    "    y_train = torch.multinomial(label_probs[0], len(y_train), replacement=True)\n",
543
    "    if len(y_val) > 0:\n",
544
    "      y_val = torch.multinomial(label_probs[1], len(y_val), replacement=True)\n",
545
    "    if len(y_test) > 0:\n",
546
    "      y_test = torch.multinomial(label_probs[2], len(y_test), replacement=True)\n",
547
    "    get_label_distribution([y_train, y_val, y_test])\n",
548
    "else:\n",
549
    "  raise ValueError(f'target_variable_type should be str or list, but is {type(target_variable_type)}')"
550
   ]
551
  },
552
  {
553
   "cell_type": "markdown",
554
   "metadata": {},
555
   "source": [
556
    "## Use additional variables for prediction"
557
   ]
558
  },
559
  {
560
   "cell_type": "code",
561
   "execution_count": 13,
562
   "metadata": {},
563
   "outputs": [
564
    {
565
     "name": "stdout",
566
     "output_type": "stream",
567
     "text": [
568
      "age_at_initial_pathologic_diagnosis\n",
569
      "Counter({5: 577, 4: 468, 6: 429, 3: 285, 7: 137, 2: 130, 1: 48, 0: 9})\n",
570
      "gender\n",
571
      "Counter({0: 1322, 1: 761})\n",
572
      "ajcc_pathologic_tumor_stage\n",
573
      "Counter({0: 398, 4: 379, 5: 276, 8: 220, 3: 185, 1: 164, 7: 162, 2: 144, 10: 77, 9: 76, 11: 1, 6: 1})\n"
574
     ]
575
    }
576
   ],
577
   "source": [
578
    "embedding_dim = 50\n",
579
    "input_list = []\n",
580
    "xs = []\n",
581
    "for v, n, t in zip(additional_variables, additional_vars, additional_var_types):\n",
582
    "  if n.startswith('age'):    \n",
583
    "    bins = [0, 20, 30, 40, 50, 60, 70, 80, 100]\n",
584
    "    v = np.digitize(v, bins)\n",
585
    "    t = 'discrete'\n",
586
    "  if t=='discrete':\n",
587
    "    target_ids, cls_id_dict = discrete_to_id(v, start=0, sort=True)\n",
588
    "    # some target_ids may have very few instances\n",
589
    "    print(n)\n",
590
    "    print(collections.Counter(target_ids))\n",
591
    "    xs.append(torch.tensor(target_ids, device=device).long())\n",
592
    "    # did not handle missing value yet\n",
593
    "    input_list.append({'in_dim': len(cls_id_dict), 'in_type': 'discrete', 'padding_idx':None, \n",
594
    "                       'embedding_dim':embedding_dim, 'hidden_dim': hidden_dim})\n",
595
    "  else: # t=='continuous'\n",
596
    "    xs.append(torch.tensor(v, device=device).float())\n",
597
    "    input_list.append({'in_dim': len(v[0]), 'in_type': 'continuous', 'hidden_dim': hidden_dim})"
598
   ]
599
  },
600
  {
601
   "cell_type": "code",
602
   "execution_count": 15,
603
   "metadata": {},
604
   "outputs": [
605
    {
606
     "name": "stdout",
607
     "output_type": "stream",
608
     "text": [
609
      "target: PFI\n",
610
      "             Variable              \t MI  \tAdj_MI\tBayes_ACC\n",
611
      "age_at_initial_pathologic_diagnosis\t0.003\t0.001 \t  0.824  \n",
612
      "              gender               \t0.009\t0.013 \t  0.824  \n",
613
      "    ajcc_pathologic_tumor_stage    \t0.012\t0.004 \t  0.824  \n",
614
      "                0-1                \t0.011\t0.003 \t  0.824  \n",
615
      "                0-2                \t0.029\t0.003 \t  0.825  \n",
616
      "                1-2                \t0.033\t0.010 \t  0.831  \n",
617
      "               0-1-2               \t0.061\t0.006 \t  0.836  \n",
618
      "target: DFI\n",
619
      "             Variable              \t MI  \tAdj_MI\tBayes_ACC\n",
620
      "age_at_initial_pathologic_diagnosis\t0.002\t0.000 \t  0.834  \n",
621
      "              gender               \t0.009\t0.013 \t  0.834  \n",
622
      "    ajcc_pathologic_tumor_stage    \t0.011\t0.004 \t  0.835  \n",
623
      "                0-1                \t0.011\t0.003 \t  0.834  \n",
624
      "                0-2                \t0.028\t0.003 \t  0.836  \n",
625
      "                1-2                \t0.029\t0.009 \t  0.838  \n",
626
      "               0-1-2               \t0.056\t0.005 \t  0.843  \n"
627
     ]
628
    }
629
   ],
630
   "source": [
631
    "if isinstance(target_variable, list):\n",
632
    "  for i, var_name in enumerate(target_variable):\n",
633
    "    if target_variable_type[i]=='discrete':\n",
634
    "      print(f'target: {var_name}')\n",
635
    "      get_mi_acc(xs, y_true=y_true[i], var_names=additional_vars, var_name_length=35)\n",
636
    "elif isinstance(target_variable, str):\n",
637
    "  if target_variable_type=='discrete':\n",
638
    "    print(f'target: {target_variable}')\n",
639
    "    get_mi_acc(xs, y_true, var_names=additional_vars, var_name_length=35)"
640
   ]
641
  },
642
  {
643
   "cell_type": "code",
644
   "execution_count": 16,
645
   "metadata": {},
646
   "outputs": [],
647
   "source": [
648
    "xs_train = [x[train_idx] for x in xs]\n",
649
    "xs_val = [x[val_idx] for x in xs]\n",
650
    "xs_test = [x[test_idx] for x in xs]"
651
   ]
652
  },
653
  {
654
   "cell_type": "code",
655
   "execution_count": 17,
656
   "metadata": {},
657
   "outputs": [
658
    {
659
     "name": "stdout",
660
     "output_type": "stream",
661
     "text": [
662
      "torch.Size([1458])\n",
663
      "torch.Size([1458])\n",
664
      "torch.Size([1458])\n",
665
      "torch.Size([1458, 10546])\n"
666
     ]
667
    }
668
   ],
669
   "source": [
670
    "last_nonlinearity = True\n",
671
    "input_list.append({'in_dim': x_train.size(1), 'in_type': 'continuous', 'hidden_dim': hidden_dim,\n",
672
    "                  'last_nonlinearity':last_nonlinearity, })\n",
673
    "xs_train.append(x_train)\n",
674
    "xs_val.append(x_val)\n",
675
    "xs_test.append(x_test)\n",
676
    "\n",
677
    "for i in xs_train:\n",
678
    "  print(i.shape)"
679
   ]
680
  },
681
  {
682
   "cell_type": "code",
683
   "execution_count": 19,
684
   "metadata": {},
685
   "outputs": [],
686
   "source": [
687
    "hidden_dim = [100]\n",
688
    "output_info = [{'hidden_dim': hidden_dim+[2]}, {'hidden_dim': hidden_dim+[2]},\n",
689
    "              {'hidden_dim': hidden_dim+[1]}]\n",
690
    "            \n",
691
    "fusion_lists = [[{'fusion_type': 'repr-weighted-avg_repr', 'hidden_dim': hidden_dim, \n",
692
    "                  'last_nonlinearity':last_nonlinearity, 'output_info': output_info}, \n",
693
    "                 {'fusion_type': 'repr-loss-avg_repr', 'hidden_dim': hidden_dim, \n",
694
    "                  'last_nonlinearity':last_nonlinearity, 'output_info': output_info},\n",
695
    "                 {'fusion_type': 'repr-avg_repr', 'hidden_dim': hidden_dim, \n",
696
    "                  'last_nonlinearity':last_nonlinearity, 'output_info': output_info},\n",
697
    "                 {'fusion_type': 'repr-cat_repr', 'hidden_dim': hidden_dim, \n",
698
    "                  'last_nonlinearity':last_nonlinearity, 'output_info': output_info},\n",
699
    "                 {'fusion_type': 'out-weighted-avg', 'output_info': output_info},\n",
700
    "                 {'fusion_type': 'out-loss-avg', 'output_info': output_info},\n",
701
    "                 {'fusion_type': 'out-avg', 'output_info': output_info}],\n",
702
    "                [{'fusion_type': 'repr-weighted-avg_repr', 'hidden_dim': hidden_dim, \n",
703
    "                  'last_nonlinearity':last_nonlinearity, 'output_info': output_info}, \n",
704
    "                 {'fusion_type': 'repr-loss-avg_repr', 'hidden_dim': hidden_dim, \n",
705
    "                  'last_nonlinearity':last_nonlinearity, 'output_info': output_info},\n",
706
    "                 {'fusion_type': 'repr-avg_repr', 'hidden_dim': hidden_dim, \n",
707
    "                  'last_nonlinearity':last_nonlinearity, 'output_info': output_info},\n",
708
    "                 {'fusion_type': 'repr-cat_repr', 'hidden_dim': hidden_dim, \n",
709
    "                  'last_nonlinearity':last_nonlinearity, 'output_info': output_info},\n",
710
    "                 {'fusion_type': 'out-weighted-avg', 'output_info': output_info},\n",
711
    "                 {'fusion_type': 'out-loss-avg', 'output_info': output_info},\n",
712
    "                 {'fusion_type': 'out-avg', 'output_info': output_info}],\n",
713
    "                [{'fusion_type': 'repr0', 'hidden_dim': hidden_dim, \n",
714
    "                  'last_nonlinearity':last_nonlinearity, 'output_info': output_info}]\n",
715
    "               ]"
716
   ]
717
  },
718
  {
719
   "cell_type": "code",
720
   "execution_count": 20,
721
   "metadata": {},
722
   "outputs": [],
723
   "source": [
724
    "model = VIN(input_list, output_info, fusion_lists, nonlinearity=nn.ReLU())\n",
725
    "if target_variable_type=='discrete':\n",
726
    "  loss_fn = nn.CrossEntropyLoss()\n",
727
    "elif target_variable_type=='dontinuous':\n",
728
    "  loss_fn = nn.MSELoss()\n",
729
    "else:\n",
730
    "  loss_fn = []\n",
731
    "  for var_type in target_variable_type:\n",
732
    "    if var_type == 'discrete':\n",
733
    "      loss_fn.append(nn.CrossEntropyLoss())\n",
734
    "    elif var_type == 'continuous':\n",
735
    "      loss_fn.append(nn.MSELoss())\n",
736
    "    else:\n",
737
    "      raise ValueError(f'target type should be either discrete or continous, but is {var_type}')"
738
   ]
739
  },
740
  {
741
   "cell_type": "code",
742
   "execution_count": 21,
743
   "metadata": {},
744
   "outputs": [],
745
   "source": [
746
    "optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), \n",
747
    "                             lr=1e-2, weight_decay=weight_decay, amsgrad=True)"
748
   ]
749
  },
750
  {
751
   "cell_type": "code",
752
   "execution_count": 22,
753
   "metadata": {
754
    "scrolled": true
755
   },
756
   "outputs": [],
757
   "source": [
758
    "for n, p in model.named_parameters():\n",
759
    "#   print(n, p.size())\n",
760
    "  if p.grad is not None and p.grad.norm()==0:\n",
761
    "    print(n, p.grad if p.grad is None else p.grad.norm())"
762
   ]
763
  },
764
  {
765
   "cell_type": "code",
766
   "execution_count": 23,
767
   "metadata": {},
768
   "outputs": [],
769
   "source": [
770
    "target_loss_weight = [1., 1., 1.]"
771
   ]
772
  },
773
  {
774
   "cell_type": "code",
775
   "execution_count": 24,
776
   "metadata": {
777
    "scrolled": true
778
   },
779
   "outputs": [
780
    {
781
     "name": "stdout",
782
     "output_type": "stream",
783
     "text": [
784
      "0 6.476935386657715\n",
785
      "99 1.0573850870132446\n"
786
     ]
787
    }
788
   ],
789
   "source": [
790
    "loss_his = []\n",
791
    "num_iters = 100\n",
792
    "print_every = 100\n",
793
    "for i in range(num_iters):\n",
794
    "  pred = model(xs_test)\n",
795
    "  losses = get_vin_loss(pred, y_test, loss_fn, model, valid_loc=None, target_id=None, \n",
796
    "                        level_weight=None)\n",
797
    "  loss = sum(losses[j][0]*target_loss_weight[j] for j in range(len(losses)))\n",
798
    "  losses = losses[0]\n",
799
    "  optimizer.zero_grad()\n",
800
    "  loss.backward()\n",
801
    "  optimizer.step()\n",
802
    "  loss_his.append([losses[0].item()] + \n",
803
    "                [[[v.item() for v in losses[1][i][0]], losses[1][i][1].item()] for i in range(2)])\n",
804
    "  if i%print_every == 0 or i==num_iters-1:\n",
805
    "    print(i, loss.item())"
806
   ]
807
  },
808
  {
809
   "cell_type": "code",
810
   "execution_count": 25,
811
   "metadata": {},
812
   "outputs": [
813
    {
814
     "name": "stdout",
815
     "output_type": "stream",
816
     "text": [
817
      "acc=1.000, precision=1.000, recall=1.000, fl=1.000, adj_MI=1.000, auc=1.000, ap=1.000, confusion_mat=\n",
818
      "[[340   0]\n",
819
      " [  0  77]]\n",
820
      "report              precision    recall  f1-score   support\n",
821
      "\n",
822
      "          0       1.00      1.00      1.00       340\n",
823
      "          1       1.00      1.00      1.00        77\n",
824
      "\n",
825
      "avg / total       1.00      1.00      1.00       417\n",
826
      "\n"
827
     ]
828
    },
829
    {
830
     "data": {
831
      "text/plain": [
832
       "[(tensor(0.3750, grad_fn=<ThAddBackward>),\n",
833
       "  [[[tensor(0.4638, grad_fn=<NllLossBackward>),\n",
834
       "     tensor(0.4475, grad_fn=<NllLossBackward>),\n",
835
       "     tensor(0.4651, grad_fn=<NllLossBackward>),\n",
836
       "     tensor(0.0441, grad_fn=<NllLossBackward>)],\n",
837
       "    tensor(0.3546, grad_fn=<ThAddBackward>)],\n",
838
       "   [[tensor(0.0055, grad_fn=<NllLossBackward>),\n",
839
       "     tensor(0.0074, grad_fn=<NllLossBackward>),\n",
840
       "     tensor(0.0078, grad_fn=<NllLossBackward>),\n",
841
       "     tensor(0.0036, grad_fn=<NllLossBackward>),\n",
842
       "     tensor(0.0263, grad_fn=<NllLossBackward>),\n",
843
       "     tensor(0.0265, grad_fn=<NllLossBackward>),\n",
844
       "     tensor(0.0267, grad_fn=<NllLossBackward>)],\n",
845
       "    tensor(0.0128, grad_fn=<ThAddBackward>)],\n",
846
       "   [[tensor(0.0036, grad_fn=<NllLossBackward>),\n",
847
       "     tensor(0.0036, grad_fn=<NllLossBackward>),\n",
848
       "     tensor(0.0037, grad_fn=<NllLossBackward>),\n",
849
       "     tensor(0.0031, grad_fn=<NllLossBackward>),\n",
850
       "     tensor(0.0083, grad_fn=<NllLossBackward>),\n",
851
       "     tensor(0.0080, grad_fn=<NllLossBackward>),\n",
852
       "     tensor(0.0091, grad_fn=<NllLossBackward>)],\n",
853
       "    tensor(0.0055, grad_fn=<ThAddBackward>)],\n",
854
       "   [[tensor(0.0021, grad_fn=<NllLossBackward>)],\n",
855
       "    tensor(0.0021, grad_fn=<AddBackward>)]]),\n",
856
       " (tensor(0.3739, grad_fn=<ThAddBackward>),\n",
857
       "  [[[tensor(0.4564, grad_fn=<NllLossBackward>),\n",
858
       "     tensor(0.4383, grad_fn=<NllLossBackward>),\n",
859
       "     tensor(0.4547, grad_fn=<NllLossBackward>),\n",
860
       "     tensor(0.0552, grad_fn=<NllLossBackward>)],\n",
861
       "    tensor(0.3481, grad_fn=<ThAddBackward>)],\n",
862
       "   [[tensor(0.0104, grad_fn=<NllLossBackward>),\n",
863
       "     tensor(0.0119, grad_fn=<NllLossBackward>),\n",
864
       "     tensor(0.0157, grad_fn=<NllLossBackward>),\n",
865
       "     tensor(0.0020, grad_fn=<NllLossBackward>),\n",
866
       "     tensor(0.0307, grad_fn=<NllLossBackward>),\n",
867
       "     tensor(0.0302, grad_fn=<NllLossBackward>),\n",
868
       "     tensor(0.0317, grad_fn=<NllLossBackward>)],\n",
869
       "    tensor(0.0178, grad_fn=<ThAddBackward>)],\n",
870
       "   [[tensor(0.0038, grad_fn=<NllLossBackward>),\n",
871
       "     tensor(0.0047, grad_fn=<NllLossBackward>),\n",
872
       "     tensor(0.0053, grad_fn=<NllLossBackward>),\n",
873
       "     tensor(0.0008, grad_fn=<NllLossBackward>),\n",
874
       "     tensor(0.0114, grad_fn=<NllLossBackward>),\n",
875
       "     tensor(0.0114, grad_fn=<NllLossBackward>),\n",
876
       "     tensor(0.0120, grad_fn=<NllLossBackward>)],\n",
877
       "    tensor(0.0068, grad_fn=<ThAddBackward>)],\n",
878
       "   [[tensor(0.0013, grad_fn=<NllLossBackward>)],\n",
879
       "    tensor(0.0013, grad_fn=<AddBackward>)]]),\n",
880
       " (tensor(0.3023, grad_fn=<ThAddBackward>),\n",
881
       "  [[[tensor(0.0833, grad_fn=<MseLossBackward>),\n",
882
       "     tensor(0.0855, grad_fn=<MseLossBackward>),\n",
883
       "     tensor(0.0839, grad_fn=<MseLossBackward>),\n",
884
       "     tensor(0.0756, grad_fn=<MseLossBackward>)],\n",
885
       "    tensor(0.0823, grad_fn=<ThAddBackward>)],\n",
886
       "   [[tensor(0.0728, grad_fn=<MseLossBackward>),\n",
887
       "     tensor(0.0724, grad_fn=<MseLossBackward>),\n",
888
       "     tensor(0.0717, grad_fn=<MseLossBackward>),\n",
889
       "     tensor(0.0723, grad_fn=<MseLossBackward>),\n",
890
       "     tensor(0.0770, grad_fn=<MseLossBackward>),\n",
891
       "     tensor(0.0770, grad_fn=<MseLossBackward>),\n",
892
       "     tensor(0.0767, grad_fn=<MseLossBackward>)],\n",
893
       "    tensor(0.0741, grad_fn=<ThAddBackward>)],\n",
894
       "   [[tensor(0.0739, grad_fn=<MseLossBackward>),\n",
895
       "     tensor(0.0723, grad_fn=<MseLossBackward>),\n",
896
       "     tensor(0.0734, grad_fn=<MseLossBackward>),\n",
897
       "     tensor(0.0714, grad_fn=<MseLossBackward>),\n",
898
       "     tensor(0.0717, grad_fn=<MseLossBackward>),\n",
899
       "     tensor(0.0717, grad_fn=<MseLossBackward>),\n",
900
       "     tensor(0.0718, grad_fn=<MseLossBackward>)],\n",
901
       "    tensor(0.0724, grad_fn=<ThAddBackward>)],\n",
902
       "   [[tensor(0.0735, grad_fn=<MseLossBackward>)],\n",
903
       "    tensor(0.0735, grad_fn=<AddBackward>)]])]"
904
      ]
905
     },
906
     "execution_count": 25,
907
     "metadata": {},
908
     "output_type": "execute_result"
909
    }
910
   ],
911
   "source": [
912
    "pred = model(xs_test)\n",
913
    "eval_classification(y_test[0], pred[0][-1][0])\n",
914
    "get_vin_loss(pred, y_test, loss_fn, model, valid_loc=None, target_id=None, \n",
915
    "                        level_weight=None)"
916
   ]
917
  },
918
  {
919
   "cell_type": "code",
920
   "execution_count": 26,
921
   "metadata": {},
922
   "outputs": [
923
    {
924
     "name": "stdout",
925
     "output_type": "stream",
926
     "text": [
927
      "acc=0.765, precision=0.736, recall=0.765, fl=0.749, adj_MI=0.007, auc=0.627, ap=0.253, confusion_mat=\n",
928
      "[[1067  133]\n",
929
      " [ 209   49]]\n",
930
      "report              precision    recall  f1-score   support\n",
931
      "\n",
932
      "          0       0.84      0.89      0.86      1200\n",
933
      "          1       0.27      0.19      0.22       258\n",
934
      "\n",
935
      "avg / total       0.74      0.77      0.75      1458\n",
936
      "\n"
937
     ]
938
    },
939
    {
940
     "data": {
941
      "text/plain": [
942
       "[(tensor(6.2221, grad_fn=<ThAddBackward>),\n",
943
       "  [[[tensor(0.4945, grad_fn=<NllLossBackward>),\n",
944
       "     tensor(0.4714, grad_fn=<NllLossBackward>),\n",
945
       "     tensor(0.4632, grad_fn=<NllLossBackward>),\n",
946
       "     tensor(2.8643, grad_fn=<NllLossBackward>)],\n",
947
       "    tensor(1.0757, grad_fn=<ThAddBackward>)],\n",
948
       "   [[tensor(1.6178, grad_fn=<NllLossBackward>),\n",
949
       "     tensor(1.8301, grad_fn=<NllLossBackward>),\n",
950
       "     tensor(1.5669, grad_fn=<NllLossBackward>),\n",
951
       "     tensor(1.8302, grad_fn=<NllLossBackward>),\n",
952
       "     tensor(0.8695, grad_fn=<NllLossBackward>),\n",
953
       "     tensor(0.8655, grad_fn=<NllLossBackward>),\n",
954
       "     tensor(0.8631, grad_fn=<NllLossBackward>)],\n",
955
       "    tensor(1.4329, grad_fn=<ThAddBackward>)],\n",
956
       "   [[tensor(1.7378, grad_fn=<NllLossBackward>),\n",
957
       "     tensor(1.7598, grad_fn=<NllLossBackward>),\n",
958
       "     tensor(1.7488, grad_fn=<NllLossBackward>),\n",
959
       "     tensor(2.0182, grad_fn=<NllLossBackward>),\n",
960
       "     tensor(1.3899, grad_fn=<NllLossBackward>),\n",
961
       "     tensor(1.4158, grad_fn=<NllLossBackward>),\n",
962
       "     tensor(1.3304, grad_fn=<NllLossBackward>)],\n",
963
       "    tensor(1.6415, grad_fn=<ThAddBackward>)],\n",
964
       "   [[tensor(2.0721, grad_fn=<NllLossBackward>)],\n",
965
       "    tensor(2.0721, grad_fn=<AddBackward>)]]),\n",
966
       " (tensor(9.2298, grad_fn=<ThAddBackward>),\n",
967
       "  [[[tensor(0.4708, grad_fn=<NllLossBackward>),\n",
968
       "     tensor(0.4488, grad_fn=<NllLossBackward>),\n",
969
       "     tensor(0.4466, grad_fn=<NllLossBackward>),\n",
970
       "     tensor(2.9583, grad_fn=<NllLossBackward>)],\n",
971
       "    tensor(1.1003, grad_fn=<ThAddBackward>)],\n",
972
       "   [[tensor(2.5054, grad_fn=<NllLossBackward>),\n",
973
       "     tensor(2.8771, grad_fn=<NllLossBackward>),\n",
974
       "     tensor(2.2349, grad_fn=<NllLossBackward>),\n",
975
       "     tensor(2.5306, grad_fn=<NllLossBackward>),\n",
976
       "     tensor(0.9175, grad_fn=<NllLossBackward>),\n",
977
       "     tensor(0.9234, grad_fn=<NllLossBackward>),\n",
978
       "     tensor(0.9039, grad_fn=<NllLossBackward>)],\n",
979
       "    tensor(1.9370, grad_fn=<ThAddBackward>)],\n",
980
       "   [[tensor(2.1666, grad_fn=<NllLossBackward>),\n",
981
       "     tensor(2.5449, grad_fn=<NllLossBackward>),\n",
982
       "     tensor(2.4155, grad_fn=<NllLossBackward>),\n",
983
       "     tensor(4.3624, grad_fn=<NllLossBackward>),\n",
984
       "     tensor(1.9025, grad_fn=<NllLossBackward>),\n",
985
       "     tensor(1.9214, grad_fn=<NllLossBackward>),\n",
986
       "     tensor(1.8252, grad_fn=<NllLossBackward>)],\n",
987
       "    tensor(2.4909, grad_fn=<ThAddBackward>)],\n",
988
       "   [[tensor(3.7016, grad_fn=<NllLossBackward>)],\n",
989
       "    tensor(3.7016, grad_fn=<AddBackward>)]]),\n",
990
       " (tensor(0.3275, grad_fn=<ThAddBackward>),\n",
991
       "  [[[tensor(0.0827, grad_fn=<MseLossBackward>),\n",
992
       "     tensor(0.0782, grad_fn=<MseLossBackward>),\n",
993
       "     tensor(0.0821, grad_fn=<MseLossBackward>),\n",
994
       "     tensor(0.0795, grad_fn=<MseLossBackward>)],\n",
995
       "    tensor(0.0807, grad_fn=<ThAddBackward>)],\n",
996
       "   [[tensor(0.0871, grad_fn=<MseLossBackward>),\n",
997
       "     tensor(0.0904, grad_fn=<MseLossBackward>),\n",
998
       "     tensor(0.0796, grad_fn=<MseLossBackward>),\n",
999
       "     tensor(0.0926, grad_fn=<MseLossBackward>),\n",
1000
       "     tensor(0.0761, grad_fn=<MseLossBackward>),\n",
1001
       "     tensor(0.0761, grad_fn=<MseLossBackward>),\n",
1002
       "     tensor(0.0760, grad_fn=<MseLossBackward>)],\n",
1003
       "    tensor(0.0827, grad_fn=<ThAddBackward>)],\n",
1004
       "   [[tensor(0.0821, grad_fn=<MseLossBackward>),\n",
1005
       "     tensor(0.0815, grad_fn=<MseLossBackward>),\n",
1006
       "     tensor(0.0803, grad_fn=<MseLossBackward>),\n",
1007
       "     tensor(0.0861, grad_fn=<MseLossBackward>),\n",
1008
       "     tensor(0.0802, grad_fn=<MseLossBackward>),\n",
1009
       "     tensor(0.0802, grad_fn=<MseLossBackward>),\n",
1010
       "     tensor(0.0800, grad_fn=<MseLossBackward>)],\n",
1011
       "    tensor(0.0815, grad_fn=<ThAddBackward>)],\n",
1012
       "   [[tensor(0.0826, grad_fn=<MseLossBackward>)],\n",
1013
       "    tensor(0.0826, grad_fn=<AddBackward>)]])]"
1014
      ]
1015
     },
1016
     "execution_count": 26,
1017
     "metadata": {},
1018
     "output_type": "execute_result"
1019
    }
1020
   ],
1021
   "source": [
1022
    "pred = model(xs_train)\n",
1023
    "eval_classification(y_train[0], pred[0][-1][0])\n",
1024
    "get_vin_loss(pred, y_train, loss_fn, model, valid_loc=None, target_id=None, \n",
1025
    "                   level_weight=None)"
1026
   ]
1027
  },
1028
  {
1029
   "cell_type": "code",
1030
   "execution_count": 27,
1031
   "metadata": {},
1032
   "outputs": [
1033
    {
1034
     "name": "stdout",
1035
     "output_type": "stream",
1036
     "text": [
1037
      "Train\n",
1038
      "acc=0.765, precision=0.736, recall=0.765, fl=0.749, adj_MI=0.007, auc=0.627, ap=0.253, confusion_mat=\n",
1039
      "[[1067  133]\n",
1040
      " [ 209   49]]\n",
1041
      "report              precision    recall  f1-score   support\n",
1042
      "\n",
1043
      "          0       0.84      0.89      0.86      1200\n",
1044
      "          1       0.27      0.19      0.22       258\n",
1045
      "\n",
1046
      "avg / total       0.74      0.77      0.75      1458\n",
1047
      "\n",
1048
      "Validataion\n",
1049
      "acc=0.808, precision=0.798, recall=0.808, fl=0.802, adj_MI=0.041, auc=0.675, ap=0.315, confusion_mat=\n",
1050
      "[[158  18]\n",
1051
      " [ 22  10]]\n",
1052
      "report              precision    recall  f1-score   support\n",
1053
      "\n",
1054
      "          0       0.88      0.90      0.89       176\n",
1055
      "          1       0.36      0.31      0.33        32\n",
1056
      "\n",
1057
      "avg / total       0.80      0.81      0.80       208\n",
1058
      "\n",
1059
      "Test\n",
1060
      "acc=1.000, precision=1.000, recall=1.000, fl=1.000, adj_MI=1.000, auc=1.000, ap=1.000, confusion_mat=\n",
1061
      "[[340   0]\n",
1062
      " [  0  77]]\n",
1063
      "report              precision    recall  f1-score   support\n",
1064
      "\n",
1065
      "          0       1.00      1.00      1.00       340\n",
1066
      "          1       1.00      1.00      1.00        77\n",
1067
      "\n",
1068
      "avg / total       1.00      1.00      1.00       417\n",
1069
      "\n"
1070
     ]
1071
    },
1072
    {
1073
     "data": {
1074
      "text/plain": [
1075
       "[(array([0.7654321 , 0.73587779, 0.7654321 , 0.74877395, 0.00738225,\n",
1076
       "         0.62744186, 0.25277694]), array([[1067,  133],\n",
1077
       "         [ 209,   49]], dtype=int64)),\n",
1078
       " (array([0.80769231, 0.7976801 , 0.80769231, 0.80236243, 0.04149792,\n",
1079
       "         0.67542614, 0.31500486]), array([[158,  18],\n",
1080
       "         [ 22,  10]], dtype=int64)),\n",
1081
       " (array([1., 1., 1., 1., 1., 1., 1.]), array([[340,   0],\n",
1082
       "         [  0,  77]], dtype=int64))]"
1083
      ]
1084
     },
1085
     "execution_count": 27,
1086
     "metadata": {},
1087
     "output_type": "execute_result"
1088
    }
1089
   ],
1090
   "source": [
1091
    "eval_classification_multi_splits(model, [xs_train, xs_val, xs_test], [y_train[0], y_val[0], y_test[0]], \n",
1092
    "  batch_size=None, multi_heads=False, cls_head=0, average='weighted', return_result=True, \n",
1093
    "  split_names=['Train', 'Validataion', 'Test'], verbose=True, \n",
1094
    "  predict_func=predict_func, pred_kwargs={'target_idx':0, 'level':-1, 'loc':0, 'train':False})"
1095
   ]
1096
  },
1097
  {
1098
   "cell_type": "markdown",
1099
   "metadata": {},
1100
   "source": [
1101
    "## Neural network models"
1102
   ]
1103
  },
1104
  {
1105
   "cell_type": "code",
1106
   "execution_count": null,
1107
   "metadata": {},
1108
   "outputs": [],
1109
   "source": [
1110
    "# loss_fn_cls = torch.nn.CrossEntropyLoss(weight=torch.tensor([0.3, 0.6], device=device))\n",
1111
    "loss_fn_cls = torch.nn.CrossEntropyLoss()\n",
1112
    "loss_fn_reg = torch.nn.MSELoss()\n",
1113
    "loss_fns = [loss_fn_cls, loss_fn_reg]\n",
1114
    "# For multiple data types, there are multiple interaction mats\n",
1115
    "feat_interact_loss_type = 'graph_laplacian'\n",
1116
    "if num_data_types > 1:\n",
1117
    "  weight_path = ['decoders', range(num_data_types), 'weight']  \n",
1118
    "else:\n",
1119
    "  weight_path = ['decoder', 'weight']\n",
1120
    "loss_feat_interact = Loss_feature_interaction(interaction_mat=interaction_mat, \n",
1121
    "                                              loss_type=feat_interact_loss_type, \n",
1122
    "                                              weight_path=weight_path, \n",
1123
    "                                              normalize=True)\n",
1124
    "other_loss_fns = [loss_feat_interact]\n",
1125
    "if num_data_types > 1:\n",
1126
    "  view_sim_loss_type = 'hub'\n",
1127
    "  explicit_target = True\n",
1128
    "  cal_target='mean-feature'\n",
1129
    "  # In this set of experiments, the encoders for all views will have the same hidden_dim\n",
1130
    "  loss_view_sim = Loss_view_similarity(sections=hidden_dim[-1], loss_type=view_sim_loss_type, \n",
1131
    "    explicit_target=explicit_target, cal_target=cal_target, target=None)\n",
1132
    "  loss_fns.append(loss_view_sim)"
1133
   ]
1134
  },
1135
  {
1136
   "cell_type": "code",
1137
   "execution_count": null,
1138
   "metadata": {},
1139
   "outputs": [],
1140
   "source": [
1141
    "model_names = []\n",
1142
    "split_names = ['train', 'val', 'test']\n",
1143
    "metric_names = ['acc', 'precision', 'recall', 'f1_score', 'adjusted_mutual_info', 'auc', \n",
1144
    "                'average_precision']\n",
1145
    "metric_all = []\n",
1146
    "confusion_mat_all = []\n",
1147
    "loss_his_all = []\n",
1148
    "acc_his_all = []"
1149
   ]
1150
  },
1151
  {
1152
   "cell_type": "code",
1153
   "execution_count": null,
1154
   "metadata": {},
1155
   "outputs": [],
1156
   "source": [
1157
    "def get_result(model, best_model, best_val_acc, best_epoch, x_train, y_train, x_val, y_val, \n",
1158
    "               x_test, y_test, batch_size, multi_heads, show_results_in_notebook=True, \n",
1159
    "               loss_idx=0, acc_idx=0):\n",
1160
    "  if len(x_val) > 0:\n",
1161
    "    print(f'Best model on validation set: best_val_acc={best_val_acc:.2f}, epoch={best_epoch}')\n",
1162
    "    metric = eval_classification_multi_splits(best_model, xs=[x_train, x_val, x_test], \n",
1163
    "      ys=[y_train, y_val, y_test], batch_size=batch_size, multi_heads=multi_heads)\n",
1164
    "\n",
1165
    "  if show_results_in_notebook:\n",
1166
    "    print('\\nModel after the last training epoch:')\n",
1167
    "    eval_classification_multi_splits(model, xs=[x_train, x_val, x_test], \n",
1168
    "                                     ys=[y_train, y_val, y_test], batch_size=batch_size, \n",
1169
    "                                     multi_heads=multi_heads, return_result=False)\n",
1170
    "\n",
1171
    "    plot_history_multi_splits([loss_train_his, loss_val_his, loss_test_his], title='Loss', \n",
1172
    "                              idx=loss_idx)\n",
1173
    "    plot_history_multi_splits([acc_train_his, acc_val_his, acc_test_his], title='Acc', idx=acc_idx)\n",
1174
    "    # scatter plot\n",
1175
    "    plot_data_multi_splits(best_model, [x_train, x_val, x_test], [y_train, y_val, y_test], \n",
1176
    "                           num_heads=2 if multi_heads else 1, \n",
1177
    "                           titles=['Training', 'Validation', 'Test'], batch_size=batch_size)\n",
1178
    "    return metric"
1179
   ]
1180
  },
1181
  {
1182
   "cell_type": "markdown",
1183
   "metadata": {},
1184
   "source": [
1185
    "# Plain deep learning model"
1186
   ]
1187
  },
1188
  {
1189
   "cell_type": "code",
1190
   "execution_count": null,
1191
   "metadata": {},
1192
   "outputs": [],
1193
   "source": [
1194
    "batch_size = 1000\n",
1195
    "print_every = 100\n",
1196
    "eval_every = 1"
1197
   ]
1198
  },
1199
  {
1200
   "cell_type": "code",
1201
   "execution_count": null,
1202
   "metadata": {},
1203
   "outputs": [],
1204
   "source": [
1205
    "in_dim = x_train.shape[1]\n",
1206
    "print('Plain deep learning model')\n",
1207
    "model_names.append('NN')\n",
1208
    "model = DenseLinear(in_dim, hidden_dim+[num_cls], dense=dense, residual=residual).to(device)\n",
1209
    "multi_heads = False\n",
1210
    "\n",
1211
    "loss_train_his = []\n",
1212
    "loss_val_his = []\n",
1213
    "loss_test_his = []\n",
1214
    "acc_train_his = []\n",
1215
    "acc_val_his = []\n",
1216
    "acc_test_his = []\n",
1217
    "best_model = model\n",
1218
    "best_val_acc = 0\n",
1219
    "best_epoch = 0"
1220
   ]
1221
  },
1222
  {
1223
   "cell_type": "code",
1224
   "execution_count": null,
1225
   "metadata": {},
1226
   "outputs": [],
1227
   "source": [
1228
    "best_model, best_val_acc, best_epoch = train_single_loss(model, x_train, y_train, \n",
1229
    "    x_val, y_val, x_test, y_test, loss_fn=loss_fn_cls, lr=lr, weight_decay=weight_decay, \n",
1230
    "    amsgrad=True, batch_size=batch_size, num_epochs=num_epochs, \n",
1231
    "    reduce_every=reduce_every, eval_every=eval_every, print_every=print_every, verbose=False, \n",
1232
    "    loss_train_his=loss_train_his, loss_val_his=loss_val_his, loss_test_his=loss_test_his, \n",
1233
    "    acc_train_his=acc_train_his, acc_val_his=acc_val_his, acc_test_his=acc_test_his, \n",
1234
    "    return_best_val=True)"
1235
   ]
1236
  },
1237
  {
1238
   "cell_type": "code",
1239
   "execution_count": null,
1240
   "metadata": {},
1241
   "outputs": [],
1242
   "source": [
1243
    "metric = get_result(model, best_model, best_val_acc, best_epoch, x_train, y_train, x_val, y_val, \n",
1244
    "                    x_test, y_test, batch_size, multi_heads, show_results_in_notebook, \n",
1245
    "                    loss_idx=0, acc_idx=0)"
1246
   ]
1247
  },
1248
  {
1249
   "cell_type": "code",
1250
   "execution_count": null,
1251
   "metadata": {},
1252
   "outputs": [],
1253
   "source": [
1254
    "loss_his_all.append([loss_train_his, loss_val_his, loss_test_his])\n",
1255
    "acc_his_all.append([acc_train_his, acc_val_his, acc_test_his])\n",
1256
    "metric_all.append([v[0] for v in metric])\n",
1257
    "confusion_mat_all.append([v[1] for v in metric])"
1258
   ]
1259
  },
1260
  {
1261
   "cell_type": "markdown",
1262
   "metadata": {},
1263
   "source": [
1264
    "# Factorization AutoEncoder"
1265
   ]
1266
  },
1267
  {
1268
   "cell_type": "code",
1269
   "execution_count": null,
1270
   "metadata": {},
1271
   "outputs": [],
1272
   "source": [
1273
    "def run_one_model(model, loss_weights, other_loss_weights, \n",
1274
    "                  loss_his_all=[], acc_his_all=[], metric_all=[], confusion_mat_all=[],\n",
1275
    "                  heads=[0,1], multi_heads=True, return_results=False, \n",
1276
    "                  loss_fns=loss_fns, other_loss_fns=other_loss_fns, \n",
1277
    "                  lr=lr, weight_decay=weight_decay, batch_size=batch_size, \n",
1278
    "                  num_epochs=num_epochs, reduce_every=reduce_every, eval_every=eval_every, \n",
1279
    "                  print_every=print_every, x_train=x_train, y_train=y_train,\n",
1280
    "                  x_val=x_val, y_val=y_val, x_test=x_test, y_test=y_test,\n",
1281
    "                  show_results_in_notebook=show_results_in_notebook):\n",
1282
    "  \"\"\"Train a model and get results  \n",
1283
    "    Most of the parameters are from the context; handle it properly\n",
1284
    "  \"\"\"\n",
1285
    "  loss_train_his = []\n",
1286
    "  loss_val_his = []\n",
1287
    "  loss_test_his = []\n",
1288
    "  acc_train_his = []\n",
1289
    "  acc_val_his = []\n",
1290
    "  acc_test_his = []\n",
1291
    "  best_model = model\n",
1292
    "  best_val_acc = 0\n",
1293
    "  best_epoch = 0\n",
1294
    "\n",
1295
    "  best_model, best_val_acc, best_epoch = train_multiloss(model, x_train, [y_train, x_train], \n",
1296
    "    x_val, [y_val, x_val], x_test, [y_test, x_test], heads=heads, loss_fns=loss_fns, \n",
1297
    "    loss_weights=loss_weights, other_loss_fns=other_loss_fns, \n",
1298
    "    other_loss_weights=other_loss_weights, \n",
1299
    "    lr=lr, weight_decay=weight_decay, batch_size=batch_size, num_epochs=num_epochs, \n",
1300
    "    reduce_every=reduce_every, eval_every=eval_every, print_every=print_every,\n",
1301
    "    loss_train_his=loss_train_his, loss_val_his=loss_val_his, loss_test_his=loss_test_his, \n",
1302
    "    acc_train_his=acc_train_his, acc_val_his=acc_val_his, acc_test_his=acc_test_his, \n",
1303
    "    return_best_val=True, amsgrad=True, verbose=False)\n",
1304
    "\n",
1305
    "  metric = get_result(model, best_model, best_val_acc, best_epoch, x_train, y_train, x_val, y_val, \n",
1306
    "                      x_test, y_test, batch_size, multi_heads, show_results_in_notebook, \n",
1307
    "                      loss_idx=0, acc_idx=0)\n",
1308
    "\n",
1309
    "  loss_his_all.append([loss_train_his, loss_val_his, loss_test_his])\n",
1310
    "  acc_his_all.append([acc_train_his, acc_val_his, acc_test_his])\n",
1311
    "  metric_all.append([v[0] for v in metric])\n",
1312
    "  confusion_mat_all.append([v[1] for v in metric])\n",
1313
    "  \n",
1314
    "  if return_results:\n",
1315
    "    return loss_his_all, acc_his_all, metric_all, confusion_mat_all"
1316
   ]
1317
  },
1318
  {
1319
   "cell_type": "code",
1320
   "execution_count": null,
1321
   "metadata": {},
1322
   "outputs": [],
1323
   "source": [
1324
    "decoder_norm = False\n",
1325
    "uniform_decoder_norm = False\n",
1326
    "print('Plain AutoEncoder model')\n",
1327
    "model_names.append('AE')\n",
1328
    "model = AutoEncoder(in_dim, hidden_dim, num_cls, dense=dense, residual=residual,\n",
1329
    "          decoder_norm=decoder_norm, uniform_decoder_norm=uniform_decoder_norm).to(device)\n",
1330
    "loss_weights = [1,1]\n",
1331
    "other_loss_weights = [0]\n",
1332
    "# heads = None should work for all the following; keep this for clarity\n",
1333
    "heads = [0,1] \n",
1334
    "run_one_model(model, loss_weights, other_loss_weights,\n",
1335
    "              loss_his_all, acc_his_all, metric_all, confusion_mat_all,\n",
1336
    "              heads=heads, multi_heads=True, return_results=False, \n",
1337
    "              loss_fns=loss_fns, other_loss_fns=other_loss_fns, \n",
1338
    "              lr=lr, weight_decay=weight_decay, batch_size=batch_size, \n",
1339
    "              num_epochs=num_epochs, reduce_every=reduce_every, eval_every=eval_every, \n",
1340
    "              print_every=print_every, x_train=x_train, y_train=y_train,\n",
1341
    "              x_val=x_val, y_val=y_val, x_test=x_test, y_test=y_test,\n",
1342
    "              show_results_in_notebook=show_results_in_notebook)"
1343
   ]
1344
  },
1345
  {
1346
   "cell_type": "markdown",
1347
   "metadata": {},
1348
   "source": [
1349
    "## Add feature interaction network regularizer"
1350
   ]
1351
  },
1352
  {
1353
   "cell_type": "code",
1354
   "execution_count": null,
1355
   "metadata": {},
1356
   "outputs": [],
1357
   "source": [
1358
    "if num_data_types > 1:\n",
1359
    "  fuse_type = 'sum'\n",
1360
    "  print('MultiviewAE with feature interaction network regularizer')\n",
1361
    "  model_names.append('MultiviewAE + feat_int')\n",
1362
    "  model = MultiviewAE(in_dims=in_dims, hidden_dims=hidden_dim, out_dim=num_cls, \n",
1363
    "                      fuse_type=fuse_type, dense=dense, residual=residual, \n",
1364
    "                      residual_layers='all', decoder_norm=decoder_norm, \n",
1365
    "                      decoder_norm_dim=0, uniform_decoder_norm=uniform_decoder_norm, \n",
1366
    "                      nonlinearity=nn.ReLU(), last_nonlinearity=True, bias=True).to(device)\n",
1367
    "else:\n",
1368
    "  print('AutoEncoder with feature interaction network regularizer')\n",
1369
    "  model_names.append('AE + feat_int')\n",
1370
    "  model = AutoEncoder(in_dim, hidden_dim, num_cls, dense=dense, residual=residual, \n",
1371
    "          decoder_norm=decoder_norm, uniform_decoder_norm=uniform_decoder_norm).to(device)\n",
1372
    "\n",
1373
    "loss_weights = [1,1]\n",
1374
    "other_loss_weights = [1]\n",
1375
    "heads = [0,1]\n",
1376
    "run_one_model(model, loss_weights, other_loss_weights, \n",
1377
    "              loss_his_all, acc_his_all, metric_all, confusion_mat_all,\n",
1378
    "              heads=heads, multi_heads=True, return_results=False, \n",
1379
    "              loss_fns=loss_fns, other_loss_fns=other_loss_fns, \n",
1380
    "              lr=lr, weight_decay=weight_decay, batch_size=batch_size, \n",
1381
    "              num_epochs=num_epochs, reduce_every=reduce_every, eval_every=eval_every, \n",
1382
    "              print_every=print_every, x_train=x_train, y_train=y_train,\n",
1383
    "              x_val=x_val, y_val=y_val, x_test=x_test, y_test=y_test,\n",
1384
    "              show_results_in_notebook=show_results_in_notebook)"
1385
   ]
1386
  },
1387
  {
1388
   "cell_type": "markdown",
1389
   "metadata": {},
1390
   "source": [
1391
    "## For multi-view data, add view similarity network regularizer"
1392
   ]
1393
  },
1394
  {
1395
   "cell_type": "code",
1396
   "execution_count": null,
1397
   "metadata": {},
1398
   "outputs": [],
1399
   "source": [
1400
    "if num_data_types > 1:\n",
1401
    "  # plain multiviewAE; compare it with plain AutoEncoder to see \n",
1402
    "  # if separating views in lower layers in MultiviewAE is better than combining them all the way\n",
1403
    "  print('Run plain MultiviewAE model')\n",
1404
    "  model_names.append('MultiviewAE')\n",
1405
    "  model = MultiviewAE(in_dims=in_dims, hidden_dims=hidden_dim, out_dim=num_cls, \n",
1406
    "                    fuse_type=fuse_type, dense=dense, residual=residual, \n",
1407
    "                    residual_layers='all', decoder_norm=decoder_norm, \n",
1408
    "                    decoder_norm_dim=0, uniform_decoder_norm=uniform_decoder_norm, \n",
1409
    "                    nonlinearity=nn.ReLU(), last_nonlinearity=True, bias=True).to(device)\n",
1410
    "\n",
1411
    "  loss_weights = [1,1]\n",
1412
    "  other_loss_weights = [0]\n",
1413
    "  heads = [0,1]\n",
1414
    "  run_one_model(model, loss_weights, other_loss_weights, \n",
1415
    "                loss_his_all, acc_his_all, metric_all, confusion_mat_all,\n",
1416
    "                heads=heads, multi_heads=True, return_results=False, \n",
1417
    "                loss_fns=loss_fns, other_loss_fns=other_loss_fns, \n",
1418
    "                lr=lr, weight_decay=weight_decay, batch_size=batch_size, \n",
1419
    "                num_epochs=num_epochs, reduce_every=reduce_every, eval_every=eval_every, \n",
1420
    "                print_every=print_every, x_train=x_train, y_train=y_train,\n",
1421
    "                x_val=x_val, y_val=y_val, x_test=x_test, y_test=y_test,\n",
1422
    "                show_results_in_notebook=show_results_in_notebook)"
1423
   ]
1424
  },
1425
  {
1426
   "cell_type": "code",
1427
   "execution_count": null,
1428
   "metadata": {},
1429
   "outputs": [],
1430
   "source": [
1431
    "if num_data_types > 1:\n",
1432
    "  print('MultiviewAE with view similarity regularizers')\n",
1433
    "  model_names.append('MultiviewAE + view_sim')\n",
1434
    "  model = MultiviewAE(in_dims=in_dims, hidden_dims=hidden_dim, out_dim=num_cls, \n",
1435
    "                      fuse_type=fuse_type, dense=dense, residual=residual, \n",
1436
    "                      residual_layers='all', decoder_norm=decoder_norm, \n",
1437
    "                      decoder_norm_dim=0, uniform_decoder_norm=uniform_decoder_norm, \n",
1438
    "                      nonlinearity=nn.ReLU(), last_nonlinearity=True, bias=True).to(device)\n",
1439
    "  loss_weights = [1,1,1]\n",
1440
    "  other_loss_weights = [0]\n",
1441
    "  heads = [0,1,2]\n",
1442
    "  run_one_model(model, loss_weights, other_loss_weights, \n",
1443
    "                loss_his_all, acc_his_all, metric_all, confusion_mat_all,\n",
1444
    "                heads=heads, multi_heads=True, return_results=False, \n",
1445
    "                loss_fns=loss_fns, other_loss_fns=other_loss_fns, \n",
1446
    "                lr=lr, weight_decay=weight_decay, batch_size=batch_size, \n",
1447
    "                num_epochs=num_epochs, reduce_every=reduce_every, eval_every=eval_every, \n",
1448
    "                print_every=print_every, x_train=x_train, y_train=y_train,\n",
1449
    "                x_val=x_val, y_val=y_val, x_test=x_test, y_test=y_test,\n",
1450
    "                show_results_in_notebook=show_results_in_notebook)"
1451
   ]
1452
  },
1453
  {
1454
   "cell_type": "code",
1455
   "execution_count": null,
1456
   "metadata": {},
1457
   "outputs": [],
1458
   "source": [
1459
    "if num_data_types > 1:\n",
1460
    "  print('MultiviewAE with both feature interaction and view similarity regularizers')\n",
1461
    "  model_names.append('MultiviewAE + feat_int + view_sim')\n",
1462
    "  model = MultiviewAE(in_dims=in_dims, hidden_dims=hidden_dim, out_dim=num_cls, \n",
1463
    "                      fuse_type=fuse_type, dense=dense, residual=residual, \n",
1464
    "                      residual_layers='all', decoder_norm=decoder_norm, \n",
1465
    "                      decoder_norm_dim=0, uniform_decoder_norm=uniform_decoder_norm, \n",
1466
    "                      nonlinearity=nn.ReLU(), last_nonlinearity=True, bias=True).to(device)\n",
1467
    "  loss_weights = [1,1,1]\n",
1468
    "  other_loss_weights = [1]\n",
1469
    "  heads = [0,1,2]\n",
1470
    "  run_one_model(model, loss_weights, other_loss_weights,\n",
1471
    "                loss_his_all, acc_his_all, metric_all, confusion_mat_all,\n",
1472
    "                heads=heads, multi_heads=True, return_results=False, \n",
1473
    "                loss_fns=loss_fns, other_loss_fns=other_loss_fns, \n",
1474
    "                lr=lr, weight_decay=weight_decay, batch_size=batch_size, \n",
1475
    "                num_epochs=num_epochs, reduce_every=reduce_every, eval_every=eval_every, \n",
1476
    "                print_every=print_every, x_train=x_train, y_train=y_train,\n",
1477
    "                x_val=x_val, y_val=y_val, x_test=x_test, y_test=y_test,\n",
1478
    "                show_results_in_notebook=show_results_in_notebook)"
1479
   ]
1480
  },
1481
  {
1482
   "cell_type": "code",
1483
   "execution_count": null,
1484
   "metadata": {},
1485
   "outputs": [],
1486
   "source": [
1487
    "with open(f'{result_folder}/{res_file}', 'wb') as f:\n",
1488
    "  print(f'Write result to file {result_folder}/{res_file}')\n",
1489
    "  pickle.dump({'loss_his_all': loss_his_all,\n",
1490
    "               'acc_his_all': acc_his_all,\n",
1491
    "               'metric_all': metric_all,\n",
1492
    "               'confusion_mat_all': confusion_mat_all,\n",
1493
    "               'model_names': model_names,\n",
1494
    "               'split_names': split_names,\n",
1495
    "               'metric_names': metric_names\n",
1496
    "              }, f)"
1497
   ]
1498
  }
1499
 ],
1500
 "metadata": {
1501
  "kernelspec": {
1502
   "display_name": "Python 3",
1503
   "language": "python",
1504
   "name": "python3"
1505
  },
1506
  "language_info": {
1507
   "codemirror_mode": {
1508
    "name": "ipython",
1509
    "version": 3
1510
   },
1511
   "file_extension": ".py",
1512
   "mimetype": "text/x-python",
1513
   "name": "python",
1514
   "nbconvert_exporter": "python",
1515
   "pygments_lexer": "ipython3",
1516
   "version": "3.6.5"
1517
  }
1518
 },
1519
 "nbformat": 4,
1520
 "nbformat_minor": 2
1521
}