-
Notifications
You must be signed in to change notification settings - Fork 16
/
kissing_detector.py
93 lines (74 loc) · 3.12 KB
/
kissing_detector.py
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
from typing import Optional
import torch
from torch import nn
import vggish
from conv import convnet_init, set_parameter_requires_grad
import conv3d
class KissingDetector(nn.Module):
def __init__(self,
conv_model_name: Optional[str],
num_classes: int,
feature_extract: bool,
use_pretrained: bool = True,
use_vggish: bool = True):
super(KissingDetector, self).__init__()
conv_output_size = 0
vggish_output_size = 0
conv_input_size = 0
conv = None
vggish_model = None
if conv_model_name:
conv, conv_input_size, conv_output_size = convnet_init(conv_model_name,
num_classes,
feature_extract,
use_pretrained)
if use_vggish:
vggish_model, vggish_output_size = vggish.vggish(feature_extract)
if not conv and not vggish_model:
raise ValueError("Use VGGish, Conv, or both")
self.conv_input_size = conv_input_size
self.conv = conv
self.vggish = vggish_model
self.combined = nn.Linear(vggish_output_size + conv_output_size, num_classes)
def forward(self, audio: torch.Tensor, image: torch.Tensor):
a = self.vggish(audio) if self.vggish else None
c = self.conv(image) if self.conv else None
if a is not None and c is not None:
combined = torch.cat((c.view(c.size(0), -1), a.view(a.size(0), -1)), dim=1)
else:
combined = a if a is not None else c
return self.combined(combined)
class KissingDetector3DConv(nn.Module):
def __init__(self,
num_classes: int,
feature_extract: bool,
use_vggish: bool = True):
super(KissingDetector3DConv, self).__init__()
conv_output_size = 512
vggish_output_size = 0
conv_input_size = 0
vggish_model = None
conv = conv3d.resnet34(
num_classes=num_classes,
shortcut_type='B',
sample_size=224,
sample_duration=16
)
set_parameter_requires_grad(conv, feature_extract)
conv.fc = nn.Identity()
if use_vggish:
vggish_model, vggish_output_size = vggish.vggish(feature_extract)
if not conv and not vggish_model:
raise ValueError("Use VGGish, Conv, or both")
self.conv_input_size = conv_input_size
self.conv = conv
self.vggish = vggish_model
self.combined = nn.Linear(vggish_output_size + conv_output_size, num_classes)
def forward(self, audio: torch.Tensor, image: torch.Tensor):
a = self.vggish(audio) if self.vggish else None
c = self.conv(image) if self.conv else None
if a is not None and c is not None:
combined = torch.cat((c.view(c.size(0), -1), a.view(a.size(0), -1)), dim=1)
else:
combined = a if a is not None else c
return self.combined(combined)