Search is not available for this dataset
repo stringlengths 2 152 ⌀ | file stringlengths 15 239 | code stringlengths 0 58.4M | file_length int64 0 58.4M | avg_line_length float64 0 1.81M | max_line_length int64 0 12.7M | extension_type stringclasses 364
values |
|---|---|---|---|---|---|---|
null | coax-main/doc/examples/pendulum/run_all.sh | #!/bin/bash
trap "kill 0" EXIT
gio trash -f ./data
for f in $(ls ./*.py); do
JAX_PLATFORM_NAME=cpu python3 $f &
done
wait
| 129 | 10.818182 | 38 | sh |
null | coax-main/doc/examples/pendulum/sac.py | import gymnasium
import jax
import coax
import haiku as hk
import jax.numpy as jnp
from numpy import prod
import optax
# the name of this script
name = 'sac'
# the Pendulum MDP
env = gymnasium.make('Pendulum-v1', render_mode='rgb_array')
env = coax.wrappers.TrainMonitor(env, name=name, tensorboard_dir=f"./data/tenso... | 4,143 | 33.533333 | 95 | py |
null | coax-main/doc/examples/pendulum/td3.py | import gymnasium
import jax
import coax
import haiku as hk
import jax.numpy as jnp
from numpy import prod
import optax
# the name of this script
name = 'td3'
# the Pendulum MDP
env = gymnasium.make('Pendulum-v1', render_mode='rgb_array')
env = coax.wrappers.TrainMonitor(env, name=name, tensorboard_dir=f"./data/tenso... | 3,593 | 29.201681 | 94 | py |
null | coax-main/doc/examples/pendulum/td4.py | import gymnasium
import jax
import coax
import haiku as hk
import jax.numpy as jnp
from numpy import prod
import optax
# the name of this script
name = 'td3'
# the Pendulum MDP
env = gymnasium.make('Pendulum-v1', render_mode='rgb_array')
env = coax.wrappers.TrainMonitor(env, name=name, tensorboard_dir=f"./data/tenso... | 4,352 | 31.244444 | 94 | py |
null | coax-main/doc/examples/pendulum/experiments/ddpg_standalone.py | """
This script is a JAX port of the original Tensorflow-based script:
https://gist.github.com/heerad/1983d50c6657a55298b67e69a2ceeb44#file-ddpg-pendulum-v0-py
"""
import os
import json
import random
from collections import deque
from functools import partial
from copy import deepcopy
import gymnasium
import ... | 10,692 | 35.872414 | 120 | py |
null | coax-main/doc/examples/stubs/a2c.py | import gymnasium
import coax
import optax
import haiku as hk
# pick environment
env = gymnasium.make(...)
env = coax.wrappers.TrainMonitor(env)
def torso(S, is_training):
# custom haiku function for the shared preprocessor
with hk.experimental.name_scope('torso'):
net = hk.Sequential([...])
retu... | 2,497 | 29.463415 | 94 | py |
null | coax-main/doc/examples/stubs/ddpg.py | import gymnasium
import coax
import optax
import haiku as hk
import jax.numpy as jnp
# pick environment
env = gymnasium.make(...)
env = coax.wrappers.TrainMonitor(env)
def func_pi(S, is_training):
# custom haiku function (for continuous actions in this example)
mu = hk.Sequential([...])(S) # mu.shape: (bat... | 2,120 | 25.848101 | 87 | py |
null | coax-main/doc/examples/stubs/dqn.py | import gymnasium
import coax
import optax
import haiku as hk
import jax
import jax.numpy as jnp
# pick environment
env = gymnasium.make(...)
env = coax.wrappers.TrainMonitor(env)
def func_type1(S, A, is_training):
# custom haiku function: s,a -> q(s,a)
value = hk.Sequential([...])
X = jax.vmap(jnp.kron)... | 1,900 | 23.688312 | 92 | py |
null | coax-main/doc/examples/stubs/dqn_per.py | import gymnasium
import coax
import optax
import haiku as hk
import jax
import jax.numpy as jnp
# pick environment
env = gymnasium.make(...)
env = coax.wrappers.TrainMonitor(env)
def func_type1(S, A, is_training):
# custom haiku function: s,a -> q(s,a)
value = hk.Sequential([...])
X = jax.vmap(jnp.kron)... | 2,170 | 25.802469 | 94 | py |
null | coax-main/doc/examples/stubs/iqn.py | import gymnasium
import coax
import optax
import haiku as hk
import jax
import jax.numpy as jnp
# pick environment
env = gymnasium.make(...)
env = coax.wrappers.TrainMonitor(env)
# choose iqn hyperparameters
quantile_embedding_dim = 32
num_quantiles = 32
def func_type1(S, A, is_training):
# custom haiku functi... | 2,227 | 26.506173 | 96 | py |
null | coax-main/doc/examples/stubs/ppo.py | import gymnasium
import coax
import optax
import haiku as hk
# pick environment
env = gymnasium.make(...)
env = coax.wrappers.TrainMonitor(env)
def func_v(S, is_training):
# custom haiku function
value = hk.Sequential([...])
return value(S) # output shape: (batch_size,)
def func_pi(S, is_training):
... | 1,935 | 26.267606 | 94 | py |
null | coax-main/doc/examples/stubs/qlearning.py | import gymnasium
import coax
import optax
import haiku as hk
import jax
import jax.numpy as jnp
# pick environment
env = gymnasium.make(...)
env = coax.wrappers.TrainMonitor(env)
def func_type1(S, A, is_training):
# custom haiku function: s,a -> q(s,a)
value = hk.Sequential([...])
X = jax.vmap(jnp.kron)... | 1,468 | 22.693548 | 92 | py |
null | coax-main/doc/examples/stubs/reinforce.py | import gymnasium
import coax
import optax
import haiku as hk
# pick environment
env = gymnasium.make(...)
env = coax.wrappers.TrainMonitor(env)
def func_pi(S, is_training):
# custom haiku function (for discrete actions in this example)
logits = hk.Sequential([...])
return {'logits': logits(S)} # logits... | 1,425 | 25.90566 | 79 | py |
null | coax-main/doc/examples/stubs/sarsa.py | import gymnasium
import coax
import optax
import haiku as hk
import jax
import jax.numpy as jnp
# pick environment
env = gymnasium.make(...)
env = coax.wrappers.TrainMonitor(env)
def func_type1(S, A, is_training):
# custom haiku function: s,a -> q(s,a)
value = hk.Sequential([...])
X = jax.vmap(jnp.kron)... | 1,474 | 22.790323 | 92 | py |
null | coax-main/doc/examples/stubs/soft_qlearning.py | import gymnasium
import coax
import haiku as hk
import jax
import jax.numpy as jnp
from optax import adam
# pick environment
env = gymnasium.make(...)
env = coax.wrappers.TrainMonitor(env)
def func_type1(S, A, is_training):
# custom haiku function: s,a -> q(s,a)
value = hk.Sequential([...])
X = jax.vmap... | 1,510 | 23.370968 | 96 | py |
null | coax-main/doc/examples/stubs/td3.py | import gymnasium
import coax
import jax
import jax.numpy as jnp
import haiku as hk
import optax
# pick environment
env = gymnasium.make(...)
env = coax.wrappers.TrainMonitor(env)
def func_pi(S, is_training):
# custom haiku function (for continuous actions in this example)
mu = hk.Sequential([...])(S) # mu.... | 2,679 | 28.130435 | 87 | py |
null | hspo-ontology-main/CODE_OF_CONDUCT.md | # Contributor Covenant Code of Conduct
This project's Code of Conduct is based on the [Contributor Covenant][homepage],
version 2.0, available at
[https://www.contributor-covenant.org/version/2/0/code_of_conduct.html](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html).
For any questions please con... | 401 | 49.25 | 143 | md |
null | hspo-ontology-main/CONTRIBUTING.md | ## Contributing
We need your help to continue to develop this project!
This project welcomes contributions from anyone interested in one or more areas covered by the HSPO ontology (e.g. healthcare, social care) or anyone interested in methods that can leverage the ontology (e.g. knowledge graphs, graph embeddings).
... | 597 | 65.444444 | 275 | md |
null | hspo-ontology-main/MAINTAINERS.md | # MAINTAINERS
- Joao Bettencourt - [@bettenj](https://github.com/bettenj)
- Natasha Mulligan - [@natasha-mulligan](https://github.ibm.com/natasha-mulligan)
Maintainers can be contacted at [jbettencourt@ie.ibm.com](mailto:jbettencourt@ie.ibm.com). | 248 | 40.5 | 90 | md |
null | hspo-ontology-main/README.md | <img width="373" alt="image" src="docs/img/hspo-logo.png">
# Health & Social Person-centric Ontology (HSPO)
[](ontology/hspo.ttl)
[](https://ibm.github.io/hspo-ontology/ont... | 4,739 | 79.338983 | 1,704 | md |
null | hspo-ontology-main/mkdocs.yml | # Health & Social Person-centric Ontology (HSPO)
site_name: Health & Social Person-centric Ontology (HSPO) User Guide
site_description: Representing a 360-view of a person (or cohort) that spans across multiple domains, from health to social.
#Repository
repo_name: Dublin-Research-Lab/hspo-ontology
repo_url: https://g... | 1,676 | 21.972603 | 124 | yml |
null | hspo-ontology-main/docs/building-kgs-hspo.md | Coming soon... | 14 | 14 | 14 | md |
null | hspo-ontology-main/docs/classes.md | # Classes
:construction: Documentation under construction.
<br/>Please see the [Ontology Specification](ontology-specification/) for further technical details.
The central point of a graph is a person (Class: Person) and has the following facets (ontology classes):
- [Disease](#disease)
- [Social Context](#social-... | 4,005 | 46.690476 | 301 | md |
null | hspo-ontology-main/docs/index.md |
<img width="173" alt="image" src="img/hspo-logo.png">
# Documentation & User Guide
[](https://pages.github.ibm.com/Dublin-Research-Lab/hspo-ontology/ontology.ttl)
[](ontolog... | 2,104 | 76.962963 | 373 | md |
null | hspo-ontology-main/docs/ontology-specification/406.html | <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>406 Not Acceptable</title>
</head>
<body>
<h1>Not Acceptable</h1>
<p>An appropriate representation of the requested resource could not be found on this server.</p>
Available variants:<ul><li><a href="index-en.html">html</a></li><li><a href="ontolog... | 493 | 48.4 | 242 | html |
null | hspo-ontology-main/docs/ontology-specification/index.html | <!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="resources/primer.css" media="screen" /> <link rel="stylesheet" href="resources/rec.css" media="screen" /> <link rel="stylesheet" href="resources/extra.css" media="screen" /> <link r... | 397,618 | 43.701405 | 694 | html |
null | hspo-ontology-main/docs/ontology-specification/resources/extra.css | body {
text-align: justify;
}
h1 {
line-height: 110%;
}
.hlist {
border: 1px solid navy;
padding:5px;
background-color: #F4FFFF;
}
.hlist li {
display: inline;
display: inline-table;
list-style-type: none;
padding-right: 20px;
}
.entity {
border: 1px solid navy;... | 1,620 | 12.072581 | 41 | css |
null | hspo-ontology-main/docs/ontology-specification/resources/owl.css | .RFC2119 {
text-transform: lowercase;
font-style: italic;
}
.nonterminal {
font-weight: bold;
font-family: sans-serif;
font-size: 95%;
}
#abstract br {
/* doesn't work right SOMETIMES
margin-bottom: 1em; */
}
.name {
font-family: monospace;
}
.buttonpanel {
margin-top: 1ex;
margin-b... | 4,389 | 16.701613 | 74 | css |
null | hspo-ontology-main/docs/ontology-specification/resources/primer.css | /* define a class "noprint" for sections which don't get printed */
.noprint { display: none; }
/* our syntax menu for switching */
div.syntaxmenu {
border: 1px dotted black;
padding:0.5em;
margin: 1em;
}
.container {
margin-right: auto;
margin-left: auto;
padding-left: 15px;
padding-right: 1... | 2,491 | 23.194175 | 107 | css |
null | hspo-ontology-main/docs/ontology-specification/resources/rec.css | /* Style for a "Recommendation" */
/*
Copyright 1997-2003 W3C (MIT, ERCIM, Keio). All Rights Reserved.
The following software licensing rules apply:
http://www.w3.org/Consortium/Legal/copyright-software */
/* $Id: base.css,v 1.25 2006/04/18 08:42:53 bbos Exp $ */
body {
padding: 2em 1em 2em 70px;
margin... | 2,459 | 26.640449 | 99 | css |
null | hspo-ontology-main/docs/ontology-specification/webvowl/index.html | <!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8" />
<meta name="author" content="Vincent Link, Steffen Lohmann, Eduard Marbach, Stefan Negru, Vitalis Wiens" />
<meta name="keywords" content="webvowl, vowl, visual notation, web ontology language, owl, rdf, ontology visualization, ontologies,... | 35,533 | 67.998058 | 1,383 | html |
null | hspo-ontology-main/docs/ontology-specification/webvowl/css/webvowl.app.css | @import url(http://fonts.googleapis.com/css?family=Open+Sans);/*----------------------------------------------
WebVOWL page
----------------------------------------------*/
html {
-ms-content-zooming: none;
}
#loading-progress {
width: 50%;
margin: 10px 0;
}
#drag_dropOverlay{
width: 100%;
... | 42,678 | 16.223164 | 110 | css |
null | hspo-ontology-main/docs/ontology-specification/webvowl/css/webvowl.css | /*-----------------------------------------------------------------
VOWL graphical elements (part of spec) - mixed CSS and SVG styles
-----------------------------------------------------------------*/
/*-------- Text --------*/
.text {
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
}
.subtext {... | 5,341 | 16.986532 | 220 | css |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/1_data_selection.py | import pandas as pd
import os
from utils_ import read_csv
def data_selection(input_path, filename, columns_to_remove, output_path):
d = read_csv(input_path + filename)
d.columns= d.columns.str.lower()
d.drop(columns_to_remove, axis=1, inplace=True)
d.to_csv(output_path + filename.lower(), index=False)... | 4,434 | 36.905983 | 97 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/2_1_data_wrangling.py | import pandas as pd
import os
from utils_ import read_csv, save_json
def check_nan(arg):
if pd.isna(arg):
return ''
else:
return arg
if __name__ == '__main__':
input_path = 'data/selected_data/'
output_path = 'data/processed_data/'
if not os.path.exists(output_path):
os.m... | 9,756 | 58.493902 | 137 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/2_2_data_wrangling_grouped_icd9.py | import pandas as pd
import os
from utils_ import read_csv, save_json
def check_nan(arg):
if pd.isna(arg):
return ''
else:
return arg
def group_icd9_code(code):
if code == '':
return ''
elif code[0] == 'E':
return code[:4]
else:
return code[:3]
if __name_... | 9,952 | 56.531792 | 138 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/3_1_data_mapping_dictionaries.py | from utils_ import read_csv, read_json, save_json, convert_to_str
import pandas as pd
def find_black_list(data, codes, key_name):
black_list = []
for k in data.keys():
for l_ in data[k][key_name]['icd9_code']:
for it in l_:
if it not in codes:
if it not i... | 4,057 | 39.58 | 123 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/3_2_data_mapping_dictionaries_grouped_icd9.py | from utils_ import read_csv, read_json, save_json, convert_to_str
import pandas as pd
def find_black_list(data, codes, key_name):
black_list = []
for k in data.keys():
for l_ in data[k][key_name]['icd9_code']:
for it in l_:
if it not in codes:
if it not i... | 3,862 | 38.824742 | 109 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/4_data_sampling.py | import argparse
from datetime import date
from utils_ import read_json, save_json
def add_record(sampled_data, data, k, ind, label):
if k not in list(sampled_data.keys()):
sampled_data[k] = {'1': {'readmission': label,
'gender': data[k]['gender'],
... | 8,858 | 76.034783 | 195 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/5_notes_info_integration.py | import os
import argparse
import pandas as pd
from utils_ import read_json, save_json, find_json_files
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--grouped_ICD9", default=None, type=int, required=True,
help = "Flag to define the input data (groupe... | 4,270 | 52.3875 | 159 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/6_1_data_analysis_overall.py | import json
from statistics import mean
from datetime import date
import pandas as pd
import argparse
import os
from utils_ import read_json
class DataAnalysis:
def __init__(self, input_path, output_path, diagnoses_dict_path1, diagnoses_dict_path2,
procedures_dict_path1, procedures_dict_path2,
... | 17,191 | 43.53886 | 144 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/6_2_data_analysis_per_group.py | import json
from statistics import mean
from datetime import date
import numpy as np
import pandas as pd
import argparse
import os
from utils_ import read_json, DataAnalysisOntMapping
class DataAnalysis:
def __init__(self, input_path, output_path, diagnoses_dict_path1, diagnoses_dict_path2,
proc... | 16,376 | 46.607558 | 144 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/6_3_data_analysis_specific_use_case.py | import json
from statistics import mean
from datetime import date
import pandas as pd
import argparse
import os
from utils_ import read_json, InputFile, DataAnalysisOntMapping
class DataAnalysis:
def __init__(self, input_path, output_path,
query_codes, query_code_descriptions,
... | 30,534 | 47.086614 | 170 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/README.md | # Person-Centric Knowledge Graph Extraction using MIMIC-III dataset: An ICU-readmission prediction study
## EHR Data Preprocessing
## Setup
### Requirements
- Python 3.7+
- numpy (tested with version 1.23.1)
- pandas (tested with version 1.4.2)
- <a target="_blank" href="https://github.com/AnthonyMRios/pymetamap">py... | 10,296 | 121.583333 | 711 | md |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/extract_explore_use_cases.py | import argparse
from utils_ import InputFile
def count_0_1_labels(file):
count_0 = 0
count_1 = 0
for k1 in file.keys():
for k2 in file[k1].keys():
if file[k1][k2]['readmission'] == '1':
count_1 += 1
else:
count_0 += 1
print('Label 0: ... | 1,368 | 40.484848 | 170 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/utils_.py | import pandas as pd
import json
import os
def read_csv(path):
return pd.read_csv(path, dtype = str)
def read_json(path):
with open(path) as json_file:
return json.load(json_file)
def save_json(file, path):
with open(path, 'w') as outfile:
json.dump(file, outfile)
def convert_to_s... | 8,969 | 37.497854 | 139 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/notes_cui_extraction/find_remaining_files_create_note_buckets.py | import pandas as pd
import argparse
import os
from utils_ import read_csv, save_json, find_json_files, remove_empty_strings
def dataframe_to_dictionary_notes(df):
notes_dict = {}
for _, row in df.iterrows():
if str(row['subject_id']) + '_' + str(int(float(row['hadm_id']))) not in notes_dict.keys():
... | 3,201 | 38.530864 | 105 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/notes_cui_extraction/map_extracted_umls_files.py | import argparse
import os
from utils_ import find_json_files, read_json, save_json
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--umls_codes_path", default=None, type=str, required=True,
help = "The path where the extracted UMLS codes are stored."... | 1,009 | 36.407407 | 108 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/notes_cui_extraction/utils_.py | import pandas as pd
import os
import json
def read_csv(path):
return pd.read_csv(path)
def read_json(path):
with open(path) as json_file:
return json.load(json_file)
def save_json(file, path):
with open(path, 'w') as outfile:
json.dump(file, outfile)
def find_json_files(folder... | 704 | 19.142857 | 44 | py |
null | hspo-ontology-main/hspo-kg-builder/data-lifting/mimic/notes_cui_extraction/MetaMap/extract_umls_codes.py | import pandas as pd
import pymetamap
import random
import os
from time import sleep
import argparse
import json
def read_csv(path):
return pd.read_csv(path)
def read_json(path):
with open(path) as json_file:
return json.load(json_file)
def save_json(file, path):
with open(path, 'w') as ... | 11,752 | 44.203846 | 191 | py |
null | hspo-ontology-main/hspo-kg-builder/kg-generation/mimic/README.md | # Person-Centric Knowledge Graph Extraction using MIMIC-III dataset: An ICU-readmission prediction study
## Knowledge Graph Generation
## Setup
### Requirements
- Python 3.7+
- rdflib (tested with version 6.1.1)
- HSPO ontology (tested with version 0.0.17)
### Execution - Description
- Run the ```graph_creation_on... | 2,144 | 70.5 | 439 | md |
null | hspo-ontology-main/hspo-kg-builder/kg-generation/mimic/graph_creation_ontology_mapping.py | from rdflib import Graph, Literal, BNode
from rdflib.term import URIRef
from rdflib.namespace import RDF
import json
import os
import argparse
from utils_ import remove_special_character_and_spaces, read_json, process_URIRef_terms
from utils_ import Ontology
class GraphMapping:
def __init__(self, input_data_path... | 20,480 | 59.594675 | 169 | py |
null | hspo-ontology-main/hspo-kg-builder/kg-generation/mimic/utils_.py | from rdflib import Graph, Namespace
from rdflib.namespace import RDF, OWL
from rdflib.term import URIRef
import json
def read_json(path):
with open(path) as json_file:
return json.load(json_file)
def process_URIRef_terms(dict_):
updated_dict_ = {}
for k in dict_.keys():
updated_d... | 2,228 | 30.394366 | 88 | py |
null | hspo-ontology-main/kg-embedding/gnn-models/mimic/0_data_split.py | import os
import random
import argparse
from helper import save_json
def find_json_files(path):
files = []
filenames = []
for file in os.listdir(path):
if file.endswith(".json"):
files.append(os.path.join(path, file))
filenames.append(file.split('.')[0])
return files, f... | 2,280 | 37.661017 | 180 | py |
null | hspo-ontology-main/kg-embedding/gnn-models/mimic/README.md | # Person-Centric Knowledge Graph Extraction using MIMIC-III dataset: An ICU-readmission prediction study
## Graph Neural Networks (GNNs)
## Setup
### Requirements
- Python 3.7+
- tqdm (tested with version 4.64.0)
- scikit-learn (tested with version 1.1.2)
- pytorch (tested with version 1.12.1)
- pytorch_geometric ... | 2,504 | 64.921053 | 260 | md |
null | hspo-ontology-main/kg-embedding/gnn-models/mimic/datasets.py | import torch_geometric.transforms as T
import torch
import os
from torch_geometric.data import Dataset
from helper import read_json
class MyDataset(Dataset):
def __init__(self, input_path, filenames, directed, add_self_loops, transform=None):
super(MyDataset, self).__init__('.', transform, None, None)
... | 1,379 | 23.210526 | 88 | py |
null | hspo-ontology-main/kg-embedding/gnn-models/mimic/helper.py | import json
import os
def save_json(file, path):
with open(path, 'w') as outfile:
json.dump(file, outfile)
def find_json_files(folder_path):
files = []
for file in os.listdir(folder_path):
if file.endswith(".json"):
files.append(os.path.join(folder_path, file))
return file... | 4,084 | 35.150442 | 108 | py |
null | hspo-ontology-main/kg-embedding/gnn-models/mimic/main.py | import argparse
import torch
from tqdm import tqdm
import os
import sys
import logging
from torch_geometric.loader import DataLoader
from torch_geometric.nn import to_hetero, to_hetero_with_bases
from sklearn.metrics import precision_recall_fscore_support, accuracy_score
from datasets import MyDataset
from models i... | 12,787 | 49.948207 | 155 | py |
null | hspo-ontology-main/kg-embedding/gnn-models/mimic/models.py | import torch
import torch.nn.functional as F
from torch_geometric.nn import SAGEConv, RGCNConv, GATv2Conv, Linear
class Net1_1(torch.nn.Module):
def __init__(self, hidden_channels):
super().__init__()
self.conv1 = SAGEConv((-1, -1), hidden_channels[0])
self.conv2 = SAGEConv((-1, -1), hidde... | 2,570 | 33.743243 | 91 | py |
null | hspo-ontology-main/kg-embedding/gnn-models/mimic/run_experiments.sh | #!/bin/bash
############################################################
# Help #
############################################################
Help()
{
# Display Help
echo "Description of parameters."
echo
echo "Example: run_experiments.sh -d 0 -s 'lm' -a... | 3,271 | 36.181818 | 393 | sh |
null | hspo-ontology-main/kg-embedding/gnn-models/mimic/utils/explore_results.py | import os
import numpy as np
import json
import argparse
class Search:
def __init__(self, folder_path, output_path):
self.folder_path = folder_path
self.output_path = output_path
self.files_to_check = self.get_files()
self.res_dict = self.build_res_dict()
self.add_avg_metri... | 7,050 | 54.960317 | 147 | py |
null | hspo-ontology-main/kg-embedding/transformation/mimic/1_graph_transformation.py | import os
import argparse
from helper import save_json
from rdflib import Graph
class GraphModUndirected:
def __init__(self, file_path, context_flag, graph_version):
self.file_path = file_path
self.context_flag = context_flag
self.init_graph = self.get_graph()
self.triplet_dict = s... | 58,295 | 67.422535 | 203 | py |
null | hspo-ontology-main/kg-embedding/transformation/mimic/2_find_graphs_with_missing_info_v4.py | # This script is used to find graphs with missing information.
# To do that we need the first version of the undirected graphs.
# Information of interest that might be missing: diseases, medication, procedures.
import argparse
from helper import save_json, read_json, find_json_files
def find_graphs_with_missing_inf... | 3,427 | 41.320988 | 113 | py |
null | hspo-ontology-main/kg-embedding/transformation/mimic/3_vocabulary.py | import argparse
import os
from helper import read_json, save_json, find_json_files, filter_list, filter_list_2
from helper import InputFile
from spacy.lang.en import English
class Vocabulary:
def __init__(self, input_path_grouped_data, input_path_graphs, directed, graph_version, extra_filter):
# Take the ... | 7,974 | 50.785714 | 168 | py |
null | hspo-ontology-main/kg-embedding/transformation/mimic/4_embedding_initialization.py | import argparse
import os
from spacy.lang.en import English
import numpy as np
from transformers import AutoTokenizer, AutoModel
import torch
from helper import read_json, save_json, find_json_files, filter_list, filter_list_2
from helper import InputFile
class Embeddings:
def __init__(self, emb_strategy, aggr_st... | 9,937 | 47.009662 | 166 | py |
null | hspo-ontology-main/kg-embedding/transformation/mimic/5_graph_preprocessing.py | import os
import argparse
import torch
import numpy as np
from torch_geometric.data import HeteroData
from helper import read_json, find_json_files
class GraphProc:
def __init__(self, graph_path, voc_path, unique_rel_triplets_path,
emb_strategy, label, output_path):
self.g = read_json(gr... | 11,030 | 55.569231 | 179 | py |
null | hspo-ontology-main/kg-embedding/transformation/mimic/README.md | # Person-Centric Knowledge Graph Extraction using MIMIC-III dataset: An ICU-readmission prediction study
## Knowledge Graph Transformation
## Setup
### Requirements
- Python 3.7+
- rdflib (tested with version 6.1.1)
- spacy (tested with version 3.4.1)
- pytorch (tested with version 1.12.1)
-... | 6,232 | 97.936508 | 412 | md |
null | hspo-ontology-main/kg-embedding/transformation/mimic/helper.py | import json
import os
def save_json(file, path):
with open(path, 'w') as outfile:
json.dump(file, outfile)
def find_json_files(folder_path):
files = []
for file in os.listdir(folder_path):
if file.endswith(".json"):
files.append(os.path.join(folder_path, file))
return file... | 3,696 | 36.343434 | 108 | py |
null | hspo-ontology-main/kg-embedding/transformation/mimic/run_graph_processing.sh | #!/bin/bash
############################################################
# Help #
############################################################
Help()
{
# Display Help
echo "Description of parameters."
echo
echo "Example: run_graph_processing.sh -g 1 -f 1 ... | 5,503 | 38.314286 | 328 | sh |
IID_representation_learning | IID_representation_learning-master/README.md | # IID representation learning
Official PyTorch implementation for the following manuscript:
[Towards IID representation learning and its application on biomedical data](https://openreview.net/forum?id=qKZH_U-tn9P), MIDL 2022. \
Jiqing Wu, Inti Zlobec, Maxime W Lafarge, Yukun He and Viktor Koelzer.
> Due to the hetero... | 9,009 | 43.60396 | 726 | md |
IID_representation_learning | IID_representation_learning-master/args.py | import random
from argparse import ArgumentParser
from pathlib import Path
def lr_type(x):
x = x.split(',')
return x[0], list(map(float, x[1:]))
def parse_args():
parser = ArgumentParser()
# basic training hyper-parameters
parser.add_argument('--seed',
type=int,
... | 6,484 | 43.115646 | 133 | py |
IID_representation_learning | IID_representation_learning-master/dataset.py | import cv2
import numpy as np
import random
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
from wilds import get_dataset
from wilds.common.data_loaders import get_train_loader, get_eval_loader
def initialize_transform(args, is_training):
""" Initialize the transforma... | 5,692 | 35.261146 | 85 | py |
IID_representation_learning | IID_representation_learning-master/environment.yml | name: iid
channels:
- defaults
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=4.5=1_gnu
- blas=1.0=mkl
- bottleneck=1.3.2=py39hdd57654_1
- brotli=1.0.9=he6710b0_2
- ca-certificates=2021.10.26=h06a4308_2
- certifi=2021.10.8=py39h06a4308_0
- cudatoolkit=11.3.1=h2bc3f7f_2
- cycler=0.11.0=pyhd3e... | 4,753 | 25.558659 | 41 | yml |
IID_representation_learning | IID_representation_learning-master/main.py | #!/usr/bin/env python3
import logging
import csv
import time
import torch
import torchvision.utils as tv_utils
import numpy as np
from argparse import Namespace
from pathlib import Path
import dataset as dataset
from args import parse_args
from restyle.models.psp import pSp
from model import ModelAndLoss
from util im... | 15,475 | 35.414118 | 125 | py |
IID_representation_learning | IID_representation_learning-master/model.py | import math
import torch
import torchvision
from torch import nn
from torch.nn import functional as F
class NoiseInjection(nn.Module):
""" The injection of morph (noise of StyleGAN) representation
to the backbone layers with different resolution
Args:
lat_chn: the channel dimension of the morph ... | 12,143 | 34.612903 | 79 | py |
IID_representation_learning | IID_representation_learning-master/util.py | import math
import random
import torch
import sys
import logging
import numpy as np
from pathlib import Path
def setup_logging(args):
""" configure the logging document that records the
critical information during training and create
args.save_dir parameter used for saving visual and training
result... | 6,566 | 32.850515 | 93 | py |
IID_representation_learning | IID_representation_learning-master/restyle/__init__.py | import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
| 82 | 19.75 | 60 | py |
IID_representation_learning | IID_representation_learning-master/restyle/configs/__init__.py | 0 | 0 | 0 | py | |
IID_representation_learning | IID_representation_learning-master/restyle/configs/data_configs.py | from configs import transforms_config
from configs.paths_config import dataset_paths
DATASETS = {
'ffhq_encode': {
'transforms': transforms_config.EncodeTransforms,
'train_source_root': dataset_paths['ffhq'],
'train_target_root': dataset_paths['ffhq'],
'test_source_root': dataset_p... | 2,575 | 40.548387 | 62 | py |
IID_representation_learning | IID_representation_learning-master/restyle/configs/paths_config.py | dataset_paths = {
'ffhq': '',
'celeba_test': '',
'cars_train': '',
'cars_test': '',
'church_train': '',
'church_test': '',
'horse_train': '',
'horse_test': '',
'afhq_wild_train': '',
'afhq_wild_test': '',
'wilds': ''
}
model_paths = {
'ir_se50': 'pretrained_models/model_ir_se50.pth',
'resnet34': 'pr... | 1,111 | 29.054054 | 78 | py |
IID_representation_learning | IID_representation_learning-master/restyle/configs/transforms_config.py | from abc import abstractmethod
import torchvision.transforms as transforms
import torch
class TransformsConfig(object):
def __init__(self, opts):
self.opts = opts
@abstractmethod
def get_transforms(self):
pass
class MedTransforms(TransformsConfig):
def __init__(self, opts):
... | 3,351 | 33.916667 | 77 | py |
IID_representation_learning | IID_representation_learning-master/restyle/criteria/__init__.py | 0 | 0 | 0 | py | |
IID_representation_learning | IID_representation_learning-master/restyle/criteria/id_loss.py | import torch
from torch import nn
from configs.paths_config import model_paths
from models.encoders.model_irse import Backbone
class IDLoss(nn.Module):
def __init__(self):
super(IDLoss, self).__init__()
print('Loading ResNet ArcFace')
self.facenet = Backbone(input_size=112, num_layers=50, ... | 1,661 | 35.933333 | 92 | py |
IID_representation_learning | IID_representation_learning-master/restyle/criteria/moco_loss.py | import torch
from torch import nn
import torch.nn.functional as F
from configs.paths_config import model_paths
class MocoLoss(nn.Module):
def __init__(self):
super(MocoLoss, self).__init__()
print("Loading MOCO model from path: {}".format(model_paths["moco"]))
self.model = self.__load_mod... | 2,638 | 36.7 | 92 | py |
IID_representation_learning | IID_representation_learning-master/restyle/criteria/w_norm.py | import torch
from torch import nn
class WNormLoss(nn.Module):
def __init__(self, start_from_latent_avg=True):
super(WNormLoss, self).__init__()
self.start_from_latent_avg = start_from_latent_avg
def forward(self, latent, latent_avg=None):
if self.start_from_latent_avg:
latent = latent - latent_avg
retu... | 379 | 24.333333 | 64 | py |
IID_representation_learning | IID_representation_learning-master/restyle/criteria/lpips/__init__.py | 0 | 0 | 0 | py | |
IID_representation_learning | IID_representation_learning-master/restyle/criteria/lpips/lpips.py | import torch
import torch.nn as nn
from criteria.lpips.networks import get_network, LinLayers
from criteria.lpips.utils import get_state_dict
class LPIPS(nn.Module):
r"""Creates a criterion that measures
Learned Perceptual Image Patch Similarity (LPIPS).
Arguments:
net_type (str): the network typ... | 1,203 | 32.444444 | 71 | py |
IID_representation_learning | IID_representation_learning-master/restyle/criteria/lpips/networks.py | from typing import Sequence
from itertools import chain
import torch
import torch.nn as nn
from torchvision import models
from criteria.lpips.utils import normalize_activation
def get_network(net_type: str):
if net_type == 'alex':
return AlexNet()
elif net_type == 'squeeze':
return SqueezeN... | 2,667 | 26.791667 | 79 | py |
IID_representation_learning | IID_representation_learning-master/restyle/criteria/lpips/utils.py | from collections import OrderedDict
import torch
def normalize_activation(x, eps=1e-10):
norm_factor = torch.sqrt(torch.sum(x ** 2, dim=1, keepdim=True))
return x / (norm_factor + eps)
def get_state_dict(net_type: str = 'alex', version: str = '0.1'):
# build url
url = 'https://raw.githubusercontent... | 885 | 27.580645 | 79 | py |
IID_representation_learning | IID_representation_learning-master/restyle/datasets/__init__.py | 0 | 0 | 0 | py | |
IID_representation_learning | IID_representation_learning-master/restyle/datasets/gt_res_dataset.py | import os
from torch.utils.data import Dataset
from PIL import Image
class GTResDataset(Dataset):
def __init__(self, root_path, gt_dir=None, transform=None, transform_train=None):
self.pairs = []
for f in os.listdir(root_path):
image_path = os.path.join(root_path, f)
gt_path = os.path.join(gt_dir, f)
i... | 839 | 27.965517 | 82 | py |
IID_representation_learning | IID_representation_learning-master/restyle/datasets/images_dataset.py | from torch.utils.data import Dataset
from PIL import Image
from utils import data_utils
class ImagesDataset(Dataset):
def __init__(self, source_root, target_root, opts, target_transform=None, source_transform=None):
self.source_paths = sorted(data_utils.make_dataset(source_root))
self.target_paths = sorted(data... | 909 | 25.764706 | 98 | py |
IID_representation_learning | IID_representation_learning-master/restyle/datasets/inference_dataset.py | from torch.utils.data import Dataset
from PIL import Image
from utils import data_utils
class InferenceDataset(Dataset):
def __init__(self, root, opts, transform=None):
self.paths = sorted(data_utils.make_dataset(root))
self.transform = transform
self.opts = opts
def __len__(self):
return len(self.paths)
... | 508 | 22.136364 | 52 | py |
IID_representation_learning | IID_representation_learning-master/restyle/editing/__init__.py | 0 | 0 | 0 | py | |
IID_representation_learning | IID_representation_learning-master/restyle/editing/inference_editing.py | import os
from argparse import Namespace
from tqdm import tqdm
import time
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader
import sys
sys.path.append(".")
sys.path.append("..")
from configs import data_configs
from datasets.inference_dataset import InferenceDataset
from e... | 6,526 | 42.805369 | 117 | py |
IID_representation_learning | IID_representation_learning-master/restyle/editing/latent_editor.py | import torch
from utils.common import tensor2im
class LatentEditor(object):
def __init__(self, stylegan_generator):
self.generator = stylegan_generator
self.interfacegan_directions = {
'age': torch.load('editing/interfacegan_directions/age.pt').cuda(),
'smile': torch.load(... | 1,446 | 41.558824 | 105 | py |
IID_representation_learning | IID_representation_learning-master/restyle/models/__init__.py | 0 | 0 | 0 | py | |
IID_representation_learning | IID_representation_learning-master/restyle/models/e4e.py | """
This file defines the core research contribution
"""
import math
import torch
from torch import nn
from models.stylegan2.model import Generator
from configs.paths_config import model_paths
from models.encoders import restyle_e4e_encoders
from utils.model_utils import RESNET_MAPPING
class e4e(nn.Module):
def... | 6,131 | 43.434783 | 120 | py |
IID_representation_learning | IID_representation_learning-master/restyle/models/psp.py | """
This file defines the core research contribution
"""
import math
import torch
from torch import nn
from models.stylegan2.model import Generator
from configs.paths_config import model_paths
from models.encoders import fpn_encoders, restyle_psp_encoders
from utils.model_utils import RESNET_MAPPING
from utils.data_ut... | 6,653 | 41.382166 | 111 | py |
IID_representation_learning | IID_representation_learning-master/restyle/models/e4e_modules/__init__.py | 0 | 0 | 0 | py |