-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathahmh.py
More file actions
49 lines (42 loc) · 1.97 KB
/
Copy pathahmh.py
File metadata and controls
49 lines (42 loc) · 1.97 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
# -*- coding: utf-8 -*-
"""AHMH.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1JsnyjP7BFWuFxbhW48dw0fudfjvGX6vL
"""
# === Custom Hierarchical Convolution Layer ===
class HierarchicalConvolution(Layer):
def __init__(self, filters, kernel_sizes, group_factors=(1, 2, 4), pool_sizes=None, **kwargs):
super(HierarchicalConvolution, self).__init__(**kwargs)
self.filters = filters
self.kernel_sizes = kernel_sizes
self.group_factors = group_factors
self.pool_sizes = pool_sizes
def build(self, input_shape):
num_resolutions = len(self.kernel_sizes)
self.conv_layers = []
for i in range(num_resolutions):
groups = input_shape[-1] // self.group_factors[i]
conv_layer = Conv2D(self.filters, self.kernel_sizes[i], activation='relu', padding='same', groups=groups)
if self.pool_sizes and i < len(self.pool_sizes):
pool_size = self.pool_sizes[i]
pooling = GlobalAveragePooling2D() if pool_size is None else AveragePooling2D(pool_size=pool_size)
conv_layer = Sequential([conv_layer, pooling])
self.conv_layers.append(conv_layer)
super(HierarchicalConvolution, self).build(input_shape)
def call(self, inputs):
conv_outputs = [conv_layer(inputs) for conv_layer in self.conv_layers]
return Concatenate(axis=-1)(conv_outputs)
def compute_output_shape(self, input_shape):
output_shape = list(input_shape)
output_shape[-1] = sum([conv.output_shape[-1] for conv in self.conv_layers])
return tuple(output_shape)
def get_config(self):
config = super(HierarchicalConvolution, self).get_config()
config.update({
'filters': self.filters,
'kernel_sizes': self.kernel_sizes,
'group_factors': self.group_factors,
'pool_sizes': self.pool_sizes
})
return config