forked from MC3-Labs/ECGFounder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinetune_model.py
More file actions
77 lines (59 loc) · 2.19 KB
/
finetune_model.py
File metadata and controls
77 lines (59 loc) · 2.19 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
import numpy as np
import pandas as pd
import torch.nn as nn
import torch.nn.functional as F
import json
from net1d import Net1D
import torch.nn as nn
import torch
def ft_12lead_ECGFounder(device, pth, n_classes, linear_prob=False):
model = Net1D(
in_channels=12,
base_filters=64, #32 64
ratio=1,
filter_list=[64,160,160,400,400,1024,1024], #[16,32,32,80,80,256,256] [32,64,64,160,160,512,512] [64,160,160,400,400,1024,1024]
m_blocks_list=[2,2,2,3,3,4,4], #[2,2,2,2,2,2,2] [2,2,2,3,3,4,4]
kernel_size=16,
stride=2,
groups_width=16,
verbose=False,
use_bn=False,
use_do=False,
n_classes=n_classes)
checkpoint = torch.load(pth, map_location=device)
state_dict = checkpoint['state_dict']
state_dict = {k: v for k, v in state_dict.items() if not k.startswith('dense.')}
model.load_state_dict(state_dict, strict=False)
model.dense = nn.Linear(model.dense.in_features, n_classes).to(device)
# freezing model
if linear_prob == True:
for name, param in model.named_parameters():
if 'dense' not in name: # no freezing last layer
param.requires_grad = False
model.to(device)
return model
def ft_1lead_ECGFounder(device, pth, n_classes,linear_prob=False):
model = Net1D(
in_channels=1,
base_filters=64, #32 64
ratio=1,
filter_list=[64,160,160,400,400,1024,1024], #[16,32,32,80,80,256,256] [32,64,64,160,160,512,512] [64,160,160,400,400,1024,1024]
m_blocks_list=[2,2,2,3,3,4,4], #[2,2,2,2,2,2,2] [2,2,2,3,3,4,4]
kernel_size=16,
stride=2,
groups_width=16,
verbose=False,
use_bn=False,
use_do=False,
n_classes=n_classes)
checkpoint = torch.load(pth, map_location=device)
state_dict = checkpoint['state_dict']
state_dict = {k: v for k, v in state_dict.items() if not k.startswith('dense.')}
model.load_state_dict(state_dict, strict=False)
model.dense = nn.Linear(model.dense.in_features, n_classes).to(device)
if linear_prob == True:
for name, param in model.named_parameters():
if 'dense' not in name: # no freezing last layer
param.requires_grad = False
model.to(device)
return model