Download this file

135 lines (117 with data), 4.5 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""
"""
from copy import deepcopy
from typing import Any, Optional, Sequence, Union
import numpy as np
import pandas as pd
import torch
from torch import Tensor
try:
import torch_ecg # noqa: F401
except ModuleNotFoundError:
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).absolute().parents[2]))
from cfg import ModelCfg
from torch_ecg.cfg import CFG
from torch_ecg.components.outputs import MultiLabelClassificationOutput
from torch_ecg.models.ecg_crnn import ECG_CRNN
__all__ = [
"ECG_CRNN_CINC2020",
]
class ECG_CRNN_CINC2020(ECG_CRNN):
""" """
__DEBUG__ = False
__name__ = "ECG_CRNN_CINC2020"
def __init__(self, classes: Sequence[str], n_leads: int, config: Optional[CFG] = None, **kwargs: Any) -> None:
"""
Parameters
----------
classes: list,
list of the classes for classification
n_leads: int,
number of leads (number of input channels)
config: dict, optional,
other hyper-parameters, including kernel sizes, etc.
ref. the corresponding config file
"""
model_config = deepcopy(ModelCfg)
model_config.update(deepcopy(config) or {})
assert n_leads == 12, "CinC2020 only supports 12-lead models"
super().__init__(classes, n_leads, model_config, **kwargs)
@torch.no_grad()
def inference(
self,
input: Union[Sequence[float], np.ndarray, Tensor],
class_names: bool = False,
bin_pred_thr: float = 0.5,
) -> MultiLabelClassificationOutput:
"""
auxiliary function to `forward`, for CINC2020,
Parameters
----------
input: array_like,
input tensor, of shape (..., channels, seq_len)
class_names: bool, default False,
if True, the returned scalar predictions will be a `DataFrame`,
with class names for each scalar prediction
bin_pred_thr: float, default 0.5,
the threshold for making binary predictions from scalar predictions
Returns
-------
MultiLabelClassificationOutput, with the following items:
classes: list,
list of the classes for classification
thr: float,
threshold for making binary predictions from scalar predictions
prob: ndarray or DataFrame,
scalar predictions, (and binary predictions if `class_names` is True)
prob: ndarray,
the array (with values 0, 1 for each class) of binary prediction
"""
if "NSR" in self.classes:
nsr_cid = self.classes.index("NSR")
elif "426783006" in self.classes:
nsr_cid = self.classes.index("426783006")
else:
nsr_cid = None
self.eval()
_input = torch.as_tensor(input, dtype=self.dtype, device=self.device)
if _input.ndim == 2:
_input = _input.unsqueeze(0) # add a batch dimension
prob = self.sigmoid(self.forward(_input))
pred = (prob >= bin_pred_thr).int()
prob = prob.cpu().detach().numpy()
pred = pred.cpu().detach().numpy()
for row_idx, row in enumerate(pred):
row_max_prob = prob[row_idx, ...].max()
if row_max_prob < ModelCfg.bin_pred_nsr_thr and nsr_cid is not None:
pred[row_idx, nsr_cid] = 1
elif row.sum() == 0:
pred[row_idx, ...] = (
((prob[row_idx, ...] + ModelCfg.bin_pred_look_again_tol) >= row_max_prob)
& (prob[row_idx, ...] >= ModelCfg.bin_pred_nsr_thr)
).astype(int)
if class_names:
prob = pd.DataFrame(prob)
prob.columns = self.classes
prob["pred"] = ""
for row_idx in range(len(prob)):
prob.at[row_idx, "pred"] = np.array(self.classes)[np.where(pred == 1)[0]].tolist()
return MultiLabelClassificationOutput(
classes=self.classes,
thr=bin_pred_thr,
prob=prob,
pred=pred,
)
@torch.no_grad()
def inference_CINC2020(
self,
input: Union[np.ndarray, Tensor],
class_names: bool = False,
bin_pred_thr: float = 0.5,
) -> MultiLabelClassificationOutput:
"""
alias for `self.inference`
"""
return self.inference(input, class_names, bin_pred_thr)