├── models
├── __init__.py
├── example_model.py
└── interspeech_model.py
├── decoda
└── .DS_Store
├── setup.py
├── complexnn
├── __init__.py
├── utils.py
├── init.py
├── dense.py
└── conv.py
├── README.md
├── working_example.py
└── LICENSE.md
/models/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/decoda/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Orkis-Research/Quaternion-Convolutional-Neural-Networks-for-End-to-End-Automatic-Speech-Recognition/HEAD/decoda/.DS_Store
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | from setuptools import setup
3 |
4 | with open('README.md') as f:
5 | DESCRIPTION = f.read()
6 |
7 |
8 | setup(
9 | name='Quaternion Convolutional Neural Networks for automatic speech recognition',
10 | version='1',
11 | license='MIT',
12 | long_description=DESCRIPTION,
13 | packages=['complexnn'],
14 | scripts=['working_example.py'],
15 | install_requires=[
16 | "numpy", "scipy", "scikit-learn", "keras", "tensorflow-gpu"]
17 |
18 | )
19 |
--------------------------------------------------------------------------------
/complexnn/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Contributors: Titouan Parcollet
5 | # Authors: Olexa Bilaniuk
6 | #
7 | # What this module includes by default:
8 |
9 | from .conv import (QuaternionConv,
10 | QuaternionConv1D,
11 | QuaternionConv2D,
12 | QuaternionConv3D)
13 |
14 | from .dense import QuaternionDense
15 | from .init import (sqrt_init, qdense_init, qconv_init)
16 | from .utils import (GetRFirst, GetIFirst, GetJFirst, GetKFirst, getpart_quaternion_output_shape_first, get_rpart_first, get_ipart_first, get_jpart_first,
17 | get_kpart_first)
18 |
19 |
20 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Quaternion-Valued Convolutional Neural Networks for End-to-End Automatic Speech Recognition
2 | =====================
3 |
4 | This repository contains the code for a simple implementation of the QCNN presented in
5 | the paper [Quaternion Convolutional Neural Networks for End-to-End Automatic Speech Recognition](https://www.researchgate.net/publication/325578506_Quaternion_Convolutional_Neural_Networks_for_End-to-End_Automatic_Speech_Recognition)
6 |
7 | Requirements & Installation
8 | ---------------------------
9 |
10 | Install all the needed dependencies with:
11 | ```
12 | python setup.py install
13 | ```
14 |
15 | Or manually:
16 | ```
17 | pip install numpy tensorflow-gpu keras scikit-learn
18 | ```
19 | Depending on your Python installation you might want to use anaconda or other tools.
20 | Note that this code works on python 2.7.13. However it has not been tested on 3.x.
21 |
22 | TIMIT
23 | -----
24 | Since the TIMIT dataset is not free, the working_example.py script does not run an experiment on this corpus. However, models used for the experiments
25 | of our paper can be found in models/interspeech_model.py.
26 |
27 |
28 |
29 | Experiment
30 | -----------
31 |
32 | 1. Run the working example:
33 |
34 | ```
35 | python working_example.py --model {QDNN, QCNN, DNN, CNN}
36 | ```
37 |
38 | The experiment is conduced on a spoken dialogues corpus which is a set of automatically transcribed human-human telephone conversations from the customer care service (CCS) of the RATP Paris transportation system. The DECODA corpus is composed of 1,242 telephone conversations, which corresponds to about 74 hours of signal. Each conversation has to be mapped to the right theme (8).
--------------------------------------------------------------------------------
/models/example_model.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Authors: Parcollet Titouan
4 | from complexnn import *
5 | import keras
6 | from keras.layers import *
7 | from keras.models import Model
8 | import keras.backend as K
9 | import numpy as np
10 |
11 | #
12 | # ConvNet
13 | #
14 |
15 | def CNN(params):
16 |
17 |
18 |
19 |
20 | if(params.model == 'QCNN'):
21 |
22 | input_seq = Input((250,4))
23 |
24 | # Conv
25 | conv = QuaternionConv1D(32, 3, strides=1, activation='relu', padding="same")(input_seq)
26 | pool = AveragePooling1D(2, padding='same')(conv)
27 | conv2 = QuaternionConv1D(64, 3, strides=1, activation='relu', padding="same")(pool)
28 | pool2 = AveragePooling1D(4, padding='same')(conv2)
29 |
30 | # Reducing dimension before Dense layer
31 | flat = Flatten()(pool2)
32 | dense = QuaternionDense(256, activation='relu')(flat)
33 |
34 | else:
35 |
36 | input_seq = Input((250,3))
37 | # Conv
38 | conv = Conv1D(32, 3, strides=1, activation='relu', padding="same")(input_seq)
39 | pool = AveragePooling1D(2, padding='same')(conv)
40 | conv2 = Conv1D(64, 3, strides=1, activation='relu', padding="same")(pool)
41 | pool2 = AveragePooling1D(4, padding='same')(conv2)
42 |
43 | # Reducing dimension before Dense layer
44 | flat = Flatten()(pool2)
45 | dense = Dense(256, activation='relu')(flat)
46 |
47 | output = Dense(8, activation='softmax')(dense)
48 | return Model(input_seq, output)
49 |
50 | #
51 | # DenseNet
52 | #
53 |
54 | def DNN(params):
55 |
56 | if(params.model == 'DNN'):
57 |
58 | input_seq = Input((250,3))
59 |
60 | I = Flatten()(input_seq)
61 |
62 | h0 = Dense(512, activation='relu')(I)
63 | d0 = Dropout(0.3)(h0)
64 | h1 = Dense(512, activation='relu')(d0)
65 | d1 = Dropout(0.3)(h1)
66 | h2 = Dense(512, activation='relu')(d1)
67 | elif(params.model == 'QDNN'):
68 |
69 | input_seq = Input((250,4))
70 |
71 | I = Flatten()(input_seq)
72 |
73 | h0 = QuaternionDense(512, activation='relu')(I)
74 | d0 = Dropout(0.3)(h0)
75 | h1 = QuaternionDense(512, activation='relu')(h0)
76 | d1 = Dropout(0.3)(h1)
77 | h2 = QuaternionDense(512, activation='relu')(h1)
78 |
79 | encoded = Dense(8, activation='softmax')(h2)
80 |
81 | return Model(input_seq, encoded);
82 |
--------------------------------------------------------------------------------
/complexnn/utils.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Authors: Titouan Parcollet
5 |
6 |
7 | import keras.backend as K
8 | from keras.layers import Layer, Lambda
9 |
10 | ######
11 | # Need to rewrite this part to have only one getter for each part
12 | #
13 | ######################
14 | # Quaternions TIMIT #
15 | ######################
16 |
17 | def get_rpart_first(x):
18 | ndim = K.ndim(x)
19 | input_shape = K.shape(x)
20 | data_format = 'channels_first'
21 | if (data_format == 'channels_first' and ndim != 3) or ndim == 2:
22 | input_dim = input_shape[1] // 4
23 | return x[:, :input_dim]
24 |
25 | input_dim = input_shape[-1] // 4
26 | if ndim == 3:
27 | return x[:, :, :input_dim]
28 | elif ndim == 4:
29 | return x[:, :, :, :input_dim]
30 | elif ndim == 5:
31 | return x[:, :, :, :, :input_dim]
32 |
33 | def get_ipart_first(x):
34 | ndim = K.ndim(x)
35 | input_shape = K.shape(x)
36 | data_format = 'channels_first'
37 | if (data_format == 'channels_first' and ndim != 3) or ndim == 2:
38 | input_dim = input_shape[1] // 4
39 | return x[:, input_dim:input_dim*2]
40 |
41 | input_dim = input_shape[-1] // 4
42 | if ndim == 3:
43 | return x[:, :, input_dim:input_dim*2]
44 | elif ndim == 4:
45 | return x[:, :, :, input_dim:input_dim*2]
46 | elif ndim == 5:
47 | return x[:, :, :, :, input_dim:input_dim*2]
48 |
49 | def get_jpart_first(x):
50 | ndim = K.ndim(x)
51 | input_shape = K.shape(x)
52 | data_format = 'channels_first'
53 | if (data_format == 'channels_first' and ndim != 3) or ndim == 2:
54 | input_dim = input_shape[1] // 4
55 | return x[:, input_dim*2:input_dim*3]
56 |
57 | input_dim = input_shape[-1] // 4
58 | if ndim == 3:
59 | return x[:, :, input_dim*2:input_dim*3]
60 | elif ndim == 4:
61 | return x[:, :, :, input_dim*2:input_dim*3]
62 | elif ndim == 5:
63 | return x[:, :, :, :, input_dim*2:input_dim*3]
64 |
65 | def get_kpart_first(x):
66 | ndim = K.ndim(x)
67 | input_shape = K.shape(x)
68 | data_format = 'channels_first'
69 | if (data_format == 'channels_first' and ndim != 3) or ndim == 2:
70 | input_dim = input_shape[1] // 4
71 | return x[:, input_dim*3:]
72 |
73 | input_dim = input_shape[-1] // 4
74 | if ndim == 3:
75 | return x[:, :, input_dim*3:]
76 | elif ndim == 4:
77 | return x[:, :, :, input_dim*3:]
78 | elif ndim == 5:
79 | return x[:, :, :, :, input_dim*3:]
80 |
81 | class GetRFirst(Layer):
82 | def call(self, inputs):
83 | return get_rpart_first(inputs)
84 | def compute_output_shape(self, input_shape):
85 | return getpart_quaternion_output_shape_first(input_shape)
86 | class GetIFirst(Layer):
87 | def call(self, inputs):
88 | return get_ipart_first(inputs)
89 | def compute_output_shape(self, input_shape):
90 | return getpart_quaternion_output_shape_first(input_shape)
91 | class GetJFirst(Layer):
92 | def call(self, inputs):
93 | return get_jpart_first(inputs)
94 | def compute_output_shape(self, input_shape):
95 | return getpart_quaternion_output_shape_first(input_shape)
96 | class GetKFirst(Layer):
97 | def call(self, inputs):
98 | return get_kpart_first(inputs)
99 | def compute_output_shape(self, input_shape):
100 | return getpart_quaternion_output_shape_first(input_shape)
101 |
102 | def getpart_quaternion_output_shape_first(input_shape):
103 | returned_shape = list(input_shape[:])
104 | image_format = K.image_data_format()
105 | ndim = len(returned_shape)
106 |
107 | data_format = 'channels_first'
108 | if (data_format == 'channels_first' and ndim != 3) or ndim == 2:
109 | axis = 1
110 | else:
111 | axis = -1
112 |
113 | returned_shape[axis] = returned_shape[axis] // 4
114 |
115 | return tuple(returned_shape)
116 |
117 |
118 |
--------------------------------------------------------------------------------
/working_example.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Authors: Parcollet Titouan
4 |
5 | import numpy as np
6 |
7 | import keras
8 | from keras.optimizers import Adam
9 | from models.example_model import *
10 | from sklearn.preprocessing import normalize
11 | import sys
12 | import argparse as Ap
13 |
14 |
15 | ##########################################
16 | ###### UTILS FOR THE EXAMPLE_SCRIPT ######
17 | ##########################################
18 |
19 | def dataPrepDecodaQuaternion(filename, isquat=True):
20 |
21 | nbTopics = 250
22 | quaternionFactor = 4
23 | realChannel = 3
24 | nbClasses = 8
25 | raw = open(filename, 'r').readlines()
26 |
27 | if(isquat):
28 | x = np.ndarray(shape=(len(raw), nbTopics, quaternionFactor))
29 | else:
30 | x = np.ndarray(shape=(len(raw), nbTopics, realChannel))
31 | y = np.ndarray(shape=(len(raw), nbClasses))
32 | elementCpt = 0
33 | documentCpt = 0
34 |
35 | for doc in raw:
36 | elements = doc.split('\t')[0].split(" ")
37 | nbElements = len(elements)
38 |
39 | # DATA
40 | for element in elements:
41 | components = element.split(',')
42 |
43 | if(isquat):
44 | x[documentCpt][elementCpt][0] = components[0]
45 | x[documentCpt][elementCpt][1] = components[1]
46 | x[documentCpt][elementCpt][2] = components[2]
47 | x[documentCpt][elementCpt][3] = components[3]
48 | else:
49 | x[documentCpt][elementCpt][0] = components[1]
50 | x[documentCpt][elementCpt][1] = components[2]
51 | x[documentCpt][elementCpt][2] = components[3]
52 |
53 | elementCpt += 1
54 | elementCpt = 0
55 |
56 | # LABELS
57 | labels = doc.split('\t')[1].split(" ")
58 | labelCpt = 0
59 | for label in labels:
60 | values = label.split(',')
61 | y[documentCpt][labelCpt] = values[0]
62 | labelCpt += 1
63 | labelCpt = 0
64 | documentCpt += 1
65 |
66 | return x,y
67 |
68 |
69 | def getArgParser():
70 | parser = Ap.ArgumentParser(description='Parameters for the Neural Networks')
71 |
72 | parser.add_argument("--lr", default="0.001", type=float)
73 | parser.add_argument("--model", "--m", default="QCNN", type=str,
74 | choices=["QCNN", "QDNN", "CNN", "DNN"])
75 |
76 | args = parser.parse_args()
77 | return args
78 |
79 | ##########################################
80 | ###### MAIN PROGRAM ######
81 | ##########################################
82 |
83 | print('####################################################')
84 | print('# Quaternion Convolutional Neural Networks #')
85 | print('# Parcollet Titouan - ORKIS - LIA - 2018 #')
86 | print('####################################################')
87 |
88 | params = getArgParser()
89 |
90 | print('Data loading -----------------------------')
91 | if(params.model in ['QCNN' , 'QDNN']):
92 | x_train, y_train = dataPrepDecodaQuaternion('decoda/250_TRAIN_Q.data',isquat=True)
93 | x_dev, y_dev = dataPrepDecodaQuaternion('decoda/250_DEV_Q.data', isquat=True)
94 | x_test, y_test = dataPrepDecodaQuaternion('decoda/250_TEST_Q.data', isquat=True)
95 | else:
96 | x_train, y_train = dataPrepDecodaQuaternion('decoda/250_TRAIN_Q.data',isquat=False)
97 | x_dev, y_dev = dataPrepDecodaQuaternion('decoda/250_DEV_Q.data', isquat=False)
98 | x_test, y_test = dataPrepDecodaQuaternion('decoda/250_TEST_Q.data', isquat=False)
99 |
100 |
101 | print('Train size : '+str(x_train.shape[0]))
102 | print('Dev size : '+str(x_dev.shape[0]))
103 | print('Test size : '+str(x_test.shape[0]))
104 |
105 | print('Parameters -------------------------------')
106 | opt = Adam(lr = 0.0005)
107 | print('learning rate : '+str(params.lr))
108 | print('Model type : '+str(params.model))
109 |
110 |
111 | #
112 | # CLASSIFIER
113 | #
114 |
115 | if(params.model in ['CNN' , 'QCNN']):
116 | classifier = CNN(params)
117 | else:
118 | classifier = DNN(params)
119 |
120 | print(' ')
121 | print('Model Summary ----------------------------')
122 | print(classifier.summary())
123 |
124 | #
125 | # Training
126 | #
127 | classifier.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
128 | classifier.fit(x_train, y_train,
129 | validation_data=(x_dev,y_dev),
130 | epochs=15,
131 | batch_size=3)
132 |
133 | #
134 | # Eval.
135 | #
136 | loss, acc = classifier.evaluate(x_test,y_test)
137 | print('Test Loss = '+str(loss)+' | Test accuracy = '+str(acc))
138 | print("That's All Folks :p ")
139 |
--------------------------------------------------------------------------------
/complexnn/init.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Contributors: Titouan Parcollet
5 | # Authors: Chiheb Trabelsi
6 |
7 | import numpy as np
8 | from numpy.random import RandomState
9 | from random import gauss
10 | import keras.backend as K
11 | from keras import initializers
12 | from keras.initializers import Initializer
13 | from keras.utils.generic_utils import (serialize_keras_object,
14 | deserialize_keras_object)
15 |
16 |
17 | #####################################################################
18 | # Quaternion Implementations #
19 | #####################################################################
20 |
21 |
22 | class qconv_init(Initializer):
23 | # The standard complex initialization using
24 | # either the He or the Glorot criterion.
25 | def __init__(self, kernel_size, input_dim,
26 | weight_dim, nb_filters=None,
27 | criterion='he', seed=None):
28 |
29 | # `weight_dim` is used as a parameter for sanity check
30 | # as we should not pass an integer as kernel_size when
31 | # the weight dimension is >= 2.
32 | # nb_filters == 0 if weights are not convolutional (matrix instead of filters)
33 | # then in such a case, weight_dim = 2.
34 | # (in case of 2D input):
35 | # nb_filters == None and len(kernel_size) == 2 and_weight_dim == 2
36 | # conv1D: len(kernel_size) == 1 and weight_dim == 1
37 | # conv2D: len(kernel_size) == 2 and weight_dim == 2
38 | # conv3d: len(kernel_size) == 3 and weight_dim == 3
39 |
40 | assert len(kernel_size) == weight_dim and weight_dim in {0, 1, 2, 3}
41 | self.nb_filters = nb_filters
42 | self.kernel_size = kernel_size
43 | self.input_dim = input_dim
44 | self.weight_dim = weight_dim
45 | self.criterion = criterion
46 | self.seed = 1337 if seed is None else seed
47 |
48 | def __call__(self, shape, dtype=None):
49 |
50 | if self.nb_filters is not None:
51 | kernel_shape = tuple(self.kernel_size) + (int(self.input_dim), self.nb_filters)
52 | else:
53 | kernel_shape = (int(self.input_dim), self.kernel_size[-1])
54 |
55 | fan_in, fan_out = initializers._compute_fans(
56 | tuple(self.kernel_size) + (self.input_dim, self.nb_filters)
57 | )
58 |
59 | # Quaternion operations start here
60 |
61 | if self.criterion == 'glorot':
62 | s = 1. / np.sqrt(2*(fan_in + fan_out))
63 | elif self.criterion == 'he':
64 | s = 1. / np.sqrt(2*fan_in)
65 | else:
66 | raise ValueError('Invalid criterion: ' + self.criterion)
67 |
68 | #Generating randoms and purely imaginary quaternions :
69 | number_of_weights = np.prod(kernel_shape)
70 | v_i = np.random.uniform(0.0,1.0,number_of_weights)
71 | v_j = np.random.uniform(0.0,1.0,number_of_weights)
72 | v_k = np.random.uniform(0.0,1.0,number_of_weights)
73 | #Make these purely imaginary quaternions unitary
74 | for i in range(0, number_of_weights):
75 | norm = np.sqrt(v_i[i]**2 + v_j[i]**2 + v_k[i]**2)+0.0001
76 | v_i[i]/= norm
77 | v_j[i]/= norm
78 | v_k[i]/= norm
79 | v_i = v_i.reshape(kernel_shape)
80 | v_j = v_j.reshape(kernel_shape)
81 | v_k = v_k.reshape(kernel_shape)
82 |
83 | rng = RandomState(self.seed)
84 | modulus = rng.rayleigh(scale=s, size=kernel_shape)
85 | phase = rng.uniform(low=-np.pi, high=np.pi, size=kernel_shape)
86 |
87 | weight_r = modulus * np.cos(phase)
88 | weight_i = modulus * v_i*np.sin(phase)
89 | weight_j = modulus * v_j*np.sin(phase)
90 | weight_k = modulus * v_k*np.sin(phase)
91 | weight = np.concatenate([weight_r, weight_i, weight_j, weight_k], axis=-1)
92 |
93 | return weight
94 |
95 | class qdense_init(Initializer):
96 | # The standard complex initialization using
97 | # either the He or the Glorot criterion.
98 | def __init__(self, shape, criterion='he', seed=None):
99 |
100 | # `weight_dim` is used as a parameter for sanity check
101 | # as we should not pass an integer as kernel_size when
102 | # the weight dimension is >= 2.
103 | # nb_filters == 0 if weights are not convolutional (matrix instead of filters)
104 | # then in such a case, weight_dim = 2.
105 | # (in case of 2D input):
106 | # nb_filters == None and len(kernel_size) == 2 and_weight_dim == 2
107 | # conv1D: len(kernel_size) == 1 and weight_dim == 1
108 | # conv2D: len(kernel_size) == 2 and weight_dim == 2
109 | # conv3d: len(kernel_size) == 3 and weight_dim == 3
110 |
111 | self.shape = shape
112 | self.criterion = criterion
113 | self.seed = 1337 if seed is None else seed
114 |
115 | def __call__(self, shape, dtype=None):
116 |
117 | fan_in = self.shape[0]
118 | fan_out = self.shape[1]
119 |
120 | # Quaternion operations start here
121 |
122 | if self.criterion == 'glorot':
123 | s = 1. / np.sqrt(2*(fan_in + fan_out))
124 | elif self.criterion == 'he':
125 | s = 1. / np.sqrt(2*fan_in)
126 | else:
127 | raise ValueError('Invalid criterion: ' + self.criterion)
128 |
129 | #Generating randoms and purely imaginary quaternions :
130 | number_of_weights = np.prod(self.shape)
131 | v_i = np.random.uniform(0.0,1.0,number_of_weights)
132 | v_j = np.random.uniform(0.0,1.0,number_of_weights)
133 | v_k = np.random.uniform(0.0,1.0,number_of_weights)
134 | #Make these purely imaginary quaternions unitary
135 | for i in range(0, number_of_weights):
136 | norm = np.sqrt(v_i[i]**2 + v_j[i]**2 + v_k[i]**2)+0.0001
137 | v_i[i]/= norm
138 | v_j[i]/= norm
139 | v_k[i]/= norm
140 | v_i = v_i.reshape(self.shape)
141 | v_j = v_j.reshape(self.shape)
142 | v_k = v_k.reshape(self.shape)
143 |
144 | rng = RandomState(self.seed)
145 | modulus = rng.rayleigh(scale=s, size=self.shape)
146 | phase = rng.uniform(low=-np.pi, high=np.pi, size=self.shape)
147 |
148 | weight_r = modulus * np.cos(phase)
149 | weight_i = modulus * v_i*np.sin(phase)
150 | weight_j = modulus * v_j*np.sin(phase)
151 | weight_k = modulus * v_k*np.sin(phase)
152 |
153 | weight = np.concatenate([weight_r, weight_i, weight_j, weight_k], axis=-1)
154 |
155 | return weight
156 |
157 | class sqrt_init(Initializer):
158 | def __call__(self, shape, dtype=None):
159 | return K.constant(1 / K.sqrt(2), shape=shape, dtype=dtype)
160 |
161 |
162 |
--------------------------------------------------------------------------------
/models/interspeech_model.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Authors: Parcollet Titouan
4 |
5 | # Imports
6 |
7 | import complexnn
8 | from complexnn import *
9 | import keras
10 | from keras.callbacks import Callback, ModelCheckpoint, LearningRateScheduler
11 | from keras.datasets import cifar10, cifar100
12 | from keras.initializers import Orthogonal
13 | from keras.layers import Layer, Dropout, AveragePooling1D, \
14 | AveragePooling2D, AveragePooling3D, add, Add, concatenate, \
15 | Concatenate, Input, Flatten, Dense, Convolution2D, BatchNormalization, \
16 | Activation, Reshape, ConvLSTM2D, Conv2D, Lambda, Permute, TimeDistributed, \
17 | SpatialDropout1D, PReLU
18 | from keras.models import Model, load_model, save_model
19 | from keras.optimizers import SGD, Adam, RMSprop
20 | from keras.preprocessing.image import ImageDataGenerator
21 | from keras.regularizers import l2
22 | from keras.utils.np_utils import to_categorical
23 | import keras.backend as K
24 | import keras.models as KM
25 | from keras.utils.training_utils import multi_gpu_model
26 | import logging as L
27 | import numpy as np
28 | import os, pdb, socket, sys, time as T
29 | from keras.backend.tensorflow_backend import set_session
30 | import tensorflow as tf
31 |
32 |
33 | #
34 | # CTC Loss
35 | #
36 |
37 | def ctc_lambda_func(args):
38 | y_pred, labels, input_length, label_length = args
39 | return K.ctc_batch_cost(labels, y_pred, input_length, label_length)
40 |
41 | #
42 | # Get Model
43 | #
44 |
45 | def getTimitModel2D(d):
46 | n = d.num_layers
47 | sf = d.start_filter
48 | activation = d.act
49 | advanced_act = d.aact
50 | drop_prob = d.dropout
51 | inputShape = (3,41,None)
52 | filsize = (3, 5)
53 | channelAxis = 1
54 |
55 | if d.aact != "none":
56 | d.act = 'linear'
57 |
58 | convArgs = {
59 | "activation": d.act,
60 | "data_format": "channels_first",
61 | "padding": "same",
62 | "bias_initializer": "zeros",
63 | "kernel_regularizer": l2(d.l2),
64 | "kernel_initializer": "random_uniform",
65 | }
66 | denseArgs = {
67 | "activation": d.act,
68 | "kernel_regularizer": l2(d.l2),
69 | "kernel_initializer": "random_uniform",
70 | "bias_initializer": "zeros",
71 | "use_bias": True
72 | }
73 |
74 | if d.model == "quaternion":
75 | convArgs.update({"kernel_initializer": d.quat_init})
76 |
77 | #
78 | # Input Layer & CTC Parameters for TIMIT
79 | #
80 | if d.model == "quaternion":
81 | I = Input(shape=(4,41,None))
82 | else:
83 | I = Input(shape=inputShape)
84 |
85 | labels = Input(name='the_labels', shape=[None], dtype='float32')
86 | input_length = Input(name='input_length', shape=[1], dtype='int64')
87 | label_length = Input(name='label_length', shape=[1], dtype='int64')
88 |
89 | #
90 | # Input stage:
91 | #
92 | if d.model == "real":
93 | O = Conv2D(sf, filsize, name='conv', use_bias=True, **convArgs)(I)
94 | if d.aact == "prelu":
95 | O = PReLU(shared_axes=[1,0])(O)
96 | else:
97 | O = QuaternionConv2D(sf, filsize, name='conv', use_bias=True, **convArgs)(I)
98 | if d.aact == "prelu":
99 | O = PReLU(shared_axes=[1,0])(O)
100 | #
101 | # Pooling
102 | #
103 | O = keras.layers.MaxPooling2D(pool_size=(1, 3), padding='same')(O)
104 |
105 |
106 | #
107 | # Stage 1
108 | #
109 | for i in xrange(0,n/2):
110 | if d.model=="real":
111 | O = Conv2D(sf, filsize, name='conv'+str(i), use_bias=True,**convArgs)(O)
112 | if d.aact == "prelu":
113 | O = PReLU(shared_axes=[1,0])(O)
114 | O = Dropout(d.dropout)(O)
115 | else:
116 | O = QuaternionConv2D(sf, filsize, name='conv'+str(i), use_bias=True, **convArgs)(O)
117 | if d.aact == "prelu":
118 | O = PReLU(shared_axes=[1,0])(O)
119 | O = Dropout(d.dropout)(O)
120 |
121 | #
122 | # Stage 2
123 | #
124 | for i in xrange(0,n/2):
125 | if d.model=="real":
126 | O = Conv2D(sf*2, filsize, name='conv'+str(i+n/2), use_bias=True, **convArgs)(O)
127 | if d.aact == "prelu":
128 | O = PReLU(shared_axes=[1,0])(O)
129 | O = Dropout(d.dropout)(O)
130 | else:
131 | O = QuaternionConv2D(sf*2, filsize, name='conv'+str(i+n/2), use_bias=True, **convArgs)(O)
132 | if d.aact == "prelu":
133 | O = PReLU(shared_axes=[1,0])(O)
134 | O = Dropout(d.dropout)(O)
135 |
136 | #
137 | # Permutation for CTC
138 | #
139 |
140 | O = Permute((3,1,2))(O)
141 | O = Lambda(lambda x: K.reshape(x, (K.shape(x)[0], K.shape(x)[1],
142 | K.shape(x)[2] * K.shape(x)[3])),
143 | output_shape=lambda x: (None, None, x[2] * x[3]))(O)
144 |
145 | #
146 | # Dense
147 | #
148 | if d.model== "quaternion":
149 | O = TimeDistributed( QuaternionDense(256, **denseArgs))(O)
150 | if d.aact == "prelu":
151 | O = PReLU(shared_axes=[1,0])(O)
152 | O = Dropout(d.dropout)(O)
153 | O = TimeDistributed( QuaternionDense(256, **denseArgs))(O)
154 | if d.aact == "prelu":
155 | O = PReLU(shared_axes=[1,0])(O)
156 | O = Dropout(d.dropout)(O)
157 | O = TimeDistributed( QuaternionDense(256, **denseArgs))(O)
158 | if d.aact == "prelu":
159 | O = PReLU(shared_axes=[1,0])(O)
160 | else:
161 | O = TimeDistributed( Dense(1024, **denseArgs))(O)
162 | if d.aact == "prelu":
163 | O = PReLU(shared_axes=[1,0])(O)
164 | O = Dropout(d.dropout)(O)
165 | O = TimeDistributed( Dense(1024, **denseArgs))(O)
166 | if d.aact == "prelu":
167 | O = PReLU(shared_axes=[1,0])(O)
168 | O = Dropout(d.dropout)(O)
169 | O = TimeDistributed( Dense(1024, **denseArgs))(O)
170 | if d.aact == "prelu":
171 | O = PReLU(shared_axes=[1,0])(O)
172 |
173 | pred = TimeDistributed( Dense(62, activation='softmax', kernel_regularizer=l2(d.l2), use_bias=True, bias_initializer="zeros", kernel_initializer='random_uniform' ))(O)
174 |
175 | #
176 | # CTC For sequence labelling
177 | #
178 | O = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([pred, labels,input_length,label_length])
179 |
180 | # Return the model
181 | #
182 | # Creating a function for testing and validation purpose
183 | #
184 | val_function = K.function([I],[pred])
185 | return Model(inputs=[I, input_length, labels, label_length], outputs=O), val_function
186 |
187 |
188 |
--------------------------------------------------------------------------------
/complexnn/dense.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | #
5 | # Authors: Titouan Parcollet
6 | #
7 |
8 | from keras import backend as K
9 | import sys; sys.path.append('.')
10 | from keras import backend as K
11 | from keras import activations, initializers, regularizers, constraints
12 | from keras.layers import Layer, InputSpec
13 | import numpy as np
14 | from .init import qdense_init
15 |
16 | class QuaternionDense(Layer):
17 | """Regular quaternion densely-connected NN layer.
18 | `QuaternionDense` implements the Hamilton product operation:
19 | where `activation` is the element-wise activation function
20 | passed as the `activation` argument, `kernel` is a weights matrix
21 | created by the layer, and `bias` is a bias vector created by the layer
22 | (only applicable if `use_bias` is `True`).
23 | Note: if the input to the layer has a rank greater than 2, then
24 | AN ERROR MESSAGE IS PRINTED.
25 | # Arguments
26 | units: Positive integer, dimensionality of each of the real part
27 | and the imaginary part. It is actualy the number of complex units.
28 | activation: Activation function to use
29 | (see keras.activations).
30 | If you don't specify anything, no activation is applied
31 | (ie. "linear" activation: `a(x) = x`).
32 | use_bias: Boolean, whether the layer uses a bias vector.
33 | kernel_initializer: Initializer for the complex `kernel` weights matrix.
34 | By default it is 'quaternion'.
35 | and the usual initializers could also be used.
36 | (see keras.initializers and init.py).
37 | bias_initializer: Initializer for the bias vector
38 | (see keras.initializers).
39 | kernel_regularizer: Regularizer function applied to
40 | the `kernel` weights matrix
41 | (see keras.regularizers).
42 | bias_regularizer: Regularizer function applied to the bias vector
43 | (see keras.regularizers).
44 | activity_regularizer: Regularizer function applied to
45 | the output of the layer (its "activation").
46 | (see keras.regularizers).
47 | kernel_constraint: Constraint function applied to the kernel matrix
48 | (see keras.constraints).
49 | bias_constraint: Constraint function applied to the bias vector
50 | (see keras.constraints).
51 | # Input shape
52 | a 2D input with shape `(batch_size, input_dim)`.
53 | # Output shape
54 | For a 2D input with shape `(batch_size, input_dim)`,
55 | the output would have shape `(batch_size, units)`.
56 | """
57 |
58 | def __init__(self, units,
59 | activation=None,
60 | use_bias=True,
61 | init_criterion='he',
62 | kernel_initializer='quaternion',
63 | bias_initializer='zeros',
64 | kernel_regularizer=None,
65 | bias_regularizer=None,
66 | activity_regularizer=None,
67 | kernel_constraint=None,
68 | bias_constraint=None,
69 | seed=None,
70 | **kwargs):
71 | if 'input_shape' not in kwargs and 'input_dim' in kwargs:
72 | kwargs['input_shape'] = (kwargs.pop('input_dim'),)
73 | super(QuaternionDense, self).__init__(**kwargs)
74 | self.units = units
75 | self.q_units = units // 4
76 | self.activation = activations.get(activation)
77 | self.use_bias = use_bias
78 | self.init_criterion = init_criterion
79 | self.kernel_initializer = kernel_initializer
80 | self.bias_initializer = initializers.get(bias_initializer)
81 | self.kernel_regularizer = regularizers.get(kernel_regularizer)
82 | self.bias_regularizer = regularizers.get(bias_regularizer)
83 | self.activity_regularizer = regularizers.get(activity_regularizer)
84 | self.kernel_constraint = constraints.get(kernel_constraint)
85 | self.bias_constraint = constraints.get(bias_constraint)
86 | if seed is None:
87 | self.seed = np.random.randint(1, 10e6)
88 | else:
89 | self.seed = seed
90 | self.input_spec = InputSpec(ndim=2)
91 | self.supports_masking = True
92 |
93 | def build(self, input_shape):
94 | assert len(input_shape) == 2
95 | assert input_shape[-1] % 2 == 0
96 | input_dim = input_shape[-1] // 4
97 | data_format = K.image_data_format()
98 | kernel_shape = (input_dim, self.units)
99 | init_shape = (input_dim, self.q_units)
100 |
101 | self.kernel_init = qdense_init(init_shape, self.init_criterion)
102 |
103 | self.kernel = self.add_weight(
104 | shape=kernel_shape,
105 | initializer=self.kernel_init,
106 | name='r',
107 | regularizer=self.kernel_regularizer,
108 | constraint=self.kernel_constraint
109 | )
110 |
111 |
112 | if self.use_bias:
113 | self.bias = self.add_weight(
114 | shape=(self.units,),
115 | initializer='zeros',
116 | name='bias',
117 | regularizer=self.bias_regularizer,
118 | constraint=self.bias_constraint
119 | )
120 | else:
121 | self.bias = None
122 |
123 | self.input_spec = InputSpec(ndim=2, axes={-1: 4 * input_dim})
124 | self.built = True
125 |
126 | def call(self, inputs):
127 | input_shape = K.shape(inputs)
128 | input_dim = input_shape[-1] // 4
129 |
130 |
131 | self.r = self.kernel[:, :self.q_units]
132 | self.i = self.kernel[:, self.q_units:self.q_units*2]
133 | self.j = self.kernel[:, self.q_units*2:self.q_units*3]
134 | self.k = self.kernel[:, self.q_units*3:]
135 |
136 | #
137 | # Concatenate to obtain Hamilton matrix
138 | #
139 | cat_kernels_4_r = K.concatenate([self.r, -self.i, -self.j, -self.k], axis=-1)
140 | cat_kernels_4_i = K.concatenate([self.i, self.r, -self.k, self.j], axis=-1)
141 | cat_kernels_4_j = K.concatenate([self.j, self.k, self.r, -self.i], axis=-1)
142 | cat_kernels_4_k = K.concatenate([self.k, -self.j, self.i, self.r], axis=-1)
143 | cat_kernels_4_quaternion = K.concatenate([cat_kernels_4_r, cat_kernels_4_i, cat_kernels_4_j, cat_kernels_4_k], axis=0)
144 |
145 | #
146 | # Perform inference
147 | #
148 |
149 | output = K.dot(inputs, cat_kernels_4_quaternion)
150 |
151 | r_input = output[:, :self.units]
152 | i_input = output[:, self.units:self.units*2]
153 | j_input = output[:, self.units*2:self.units*3]
154 | k_input = output[:, self.units*3:]
155 |
156 |
157 | output = K.concatenate([r_input, i_input, j_input, k_input], axis = -1)
158 |
159 | if self.use_bias:
160 | output = K.bias_add(output, self.bias)
161 | if self.activation is not None:
162 | output = self.activation(output)
163 |
164 | return output
165 |
166 | def compute_output_shape(self, input_shape):
167 | assert input_shape and len(input_shape) == 2
168 | assert input_shape[-1]
169 | output_shape = list(input_shape)
170 | output_shape[-1] = self.units
171 | return tuple(output_shape)
172 |
173 | def get_config(self):
174 | if self.kernel_initializer == 'quaternion':
175 | ki = self.kernel_init
176 | else:
177 | ki = initializers.serialize(self.kernel_initializer)
178 | config = {
179 | 'units': self.units,
180 | 'activation': activations.serialize(self.activation),
181 | 'use_bias': self.use_bias,
182 | 'init_criterion': self.init_criterion,
183 | 'kernel_initializer': ki,
184 | 'bias_initializer': initializers.serialize(self.bias_initializer),
185 | 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),
186 | 'bias_regularizer': regularizers.serialize(self.bias_regularizer),
187 | 'activity_regularizer': regularizers.serialize(self.activity_regularizer),
188 | 'kernel_constraint': constraints.serialize(self.kernel_constraint),
189 | 'bias_constraint': constraints.serialize(self.bias_constraint),
190 | 'seed': self.seed,
191 | }
192 | base_config = super(QuaternionDense, self).get_config()
193 | return dict(list(base_config.items()) + list(config.items()))
194 |
195 |
196 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/complexnn/conv.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Contributors : Titouan Parcollet
5 | # Initial Authors: Chiheb Trabelsi
6 |
7 | from keras import backend as K
8 | from keras import activations, initializers, regularizers, constraints
9 | from keras.layers import Lambda, Layer, InputSpec, Convolution1D, Convolution2D, add, multiply, Activation, Input, concatenate
10 | from keras.layers.convolutional import _Conv
11 | from keras.layers.merge import _Merge
12 | from keras.layers.recurrent import Recurrent
13 | from keras.utils import conv_utils
14 | from keras.models import Model
15 | import numpy as np
16 | from .init import *
17 | import sys
18 |
19 |
20 | #####################################################################
21 | # Quaternion Implementations #
22 | #####################################################################
23 |
24 | class QuaternionConv(Layer):
25 | """Abstract nD quaternion convolution layer.
26 | This layer creates a quaternion convolution kernel that is convolved
27 | with the layer input to produce a tensor of outputs.
28 | If `use_bias` is True, a bias vector is created and added to the outputs.
29 | Finally, if `activation` is not `None`,
30 | it is applied to the outputs as well.
31 | # Arguments
32 | rank: An integer, the rank of the convolution,
33 | e.g. "2" for 2D convolution.
34 | filters: Integer, the dimensionality of the output space, i.e,
35 | the number of quaternion feature maps. It is also the effective number
36 | of feature maps for each of the real and imaginary parts.
37 | (i.e. the number of quaternion filters in the convolution)
38 | The total effective number of filters is 2 x filters.
39 | kernel_size: An integer or tuple/list of n integers, specifying the
40 | dimensions of the convolution window.
41 | strides: An integer or tuple/list of n integers,
42 | spfying the strides of the convolution.
43 | Specifying any stride value != 1 is incompatible with specifying
44 | any `dilation_rate` value != 1.
45 | padding: One of `"valid"` or `"same"` (case-insensitive).
46 | data_format: A string,
47 | one of `channels_last` (default) or `channels_first`.
48 | The ordering of the dimensions in the inputs.
49 | `channels_last` corresponds to inputs with shape
50 | `(batch, ..., channels)` while `channels_first` corresponds to
51 | inputs with shape `(batch, channels, ...)`.
52 | It defaults to the `image_data_format` value found in your
53 | Keras config file at `~/.keras/keras.json`.
54 | If you never set it, then it will be "channels_last".
55 | dilation_rate: An integer or tuple/list of n integers, specifying
56 | the dilation rate to use for dilated convolution.
57 | Currently, specifying any `dilation_rate` value != 1 is
58 | incompatible with specifying any `strides` value != 1.
59 | activation: Activation function to use
60 | (see keras.activations).
61 | If you don't specify anything, no activation is applied
62 | (ie. "linear" activation: `a(x) = x`).
63 | use_bias: Boolean, whether the layer uses a bias vector.
64 | normalize_weight: Boolean, whether the layer normalizes its quaternion
65 | weights before convolving the quaternion input.
66 | The quaternion normalization performed is similar to the one
67 | for the batchnorm. Each of the quaternion kernels are centred and multiplied by
68 | the inverse square root of covariance matrix.
69 | Then, a quaternion multiplication is perfromed as the normalized weights are
70 | multiplied by the quaternion scaling factor gamma.
71 | kernel_initializer: Initializer for the quaternion `kernel` weights matrix.
72 | By default it is 'quaternion'. The 'quaternion_independent'
73 | and the usual initializers could also be used.
74 | (see keras.initializers and init.py).
75 | bias_initializer: Initializer for the bias vector
76 | (see keras.initializers).
77 | kernel_regularizer: Regularizer function applied to
78 | the `kernel` weights matrix
79 | (see keras.regularizers).
80 | bias_regularizer: Regularizer function applied to the bias vector
81 | (see keras.regularizers).
82 | activity_regularizer: Regularizer function applied to
83 | the output of the layer (its "activation").
84 | (see keras.regularizers).
85 | kernel_constraint: Constraint function applied to the kernel matrix
86 | (see keras.constraints).
87 | bias_constraint: Constraint function applied to the bias vector
88 | (see keras.constraints).
89 | spectral_parametrization: Whether or not to use a spectral
90 | parametrization of the parameters.
91 | """
92 |
93 | def __init__(self, rank,
94 | filters,
95 | kernel_size,
96 | strides=1,
97 | padding='valid',
98 | data_format='channels_last',
99 | dilation_rate=1,
100 | activation=None,
101 | use_bias=True,
102 | normalize_weight=False,
103 | kernel_initializer='quaternion',
104 | bias_initializer='zeros',
105 | gamma_diag_initializer=sqrt_init,
106 | gamma_off_initializer='zeros',
107 | kernel_regularizer=None,
108 | bias_regularizer=None,
109 | gamma_diag_regularizer=None,
110 | gamma_off_regularizer=None,
111 | activity_regularizer=None,
112 | kernel_constraint=None,
113 | bias_constraint=None,
114 | gamma_diag_constraint=None,
115 | gamma_off_constraint=None,
116 | init_criterion='he',
117 | seed=None,
118 | spectral_parametrization=False,
119 | epsilon=1e-7,
120 | **kwargs):
121 | super(QuaternionConv, self).__init__(**kwargs)
122 | self.rank = rank
123 | self.filters = filters
124 | self.kernel_size = conv_utils.normalize_tuple(kernel_size, rank, 'kernel_size')
125 | self.strides = conv_utils.normalize_tuple(strides, rank, 'strides')
126 | self.padding = conv_utils.normalize_padding(padding)
127 | self.data_format = K.normalize_data_format(data_format)
128 | self.dilation_rate = conv_utils.normalize_tuple(dilation_rate, rank, 'dilation_rate')
129 | self.activation = activations.get(activation)
130 | self.use_bias = use_bias
131 | self.normalize_weight = normalize_weight
132 | self.init_criterion = init_criterion
133 | self.spectral_parametrization = spectral_parametrization
134 | self.epsilon = epsilon
135 | self.kernel_initializer = sanitizedInitGet(kernel_initializer)
136 | self.bias_initializer = sanitizedInitGet(bias_initializer)
137 | self.gamma_diag_initializer = sanitizedInitGet(gamma_diag_initializer)
138 | self.gamma_off_initializer = sanitizedInitGet(gamma_off_initializer)
139 | self.kernel_regularizer = regularizers.get(kernel_regularizer)
140 | self.bias_regularizer = regularizers.get(bias_regularizer)
141 | self.gamma_diag_regularizer = regularizers.get(gamma_diag_regularizer)
142 | self.gamma_off_regularizer = regularizers.get(gamma_off_regularizer)
143 | self.activity_regularizer = regularizers.get(activity_regularizer)
144 | self.kernel_constraint = constraints.get(kernel_constraint)
145 | self.bias_constraint = constraints.get(bias_constraint)
146 | self.gamma_diag_constraint = constraints.get(gamma_diag_constraint)
147 | self.gamma_off_constraint = constraints.get(gamma_off_constraint)
148 | if seed is None:
149 | self.seed = np.random.randint(1, 10e6)
150 | else:
151 | self.seed = seed
152 | self.input_spec = InputSpec(ndim=self.rank + 2)
153 |
154 | def build(self, input_shape):
155 |
156 | if self.data_format == 'channels_first':
157 | channel_axis = 1
158 | else:
159 | channel_axis = -1
160 |
161 | if input_shape[channel_axis] is None:
162 | raise ValueError('The channel dimension of the inputs '
163 | 'should be defined. Found `None`.')
164 | input_dim = input_shape[channel_axis] // 4
165 | self.kernel_shape = self.kernel_size + (input_dim , self.filters)
166 |
167 | kls = {'quaternion': qconv_init}[self.kernel_initializer]
168 | kern_init = kls(
169 | kernel_size=self.kernel_size,
170 | input_dim=input_dim,
171 | weight_dim=self.rank,
172 | nb_filters=self.filters,
173 | criterion=self.init_criterion)
174 |
175 | self.kernel = self.add_weight(
176 | self.kernel_shape,
177 | initializer=kern_init,
178 | name='kernel',
179 | regularizer=self.kernel_regularizer,
180 | constraint=self.kernel_constraint
181 | )
182 |
183 | if self.normalize_weight:
184 | gamma_shape = (input_dim * self.filters,)
185 | self.gamma_rr = self.add_weight(
186 | shape=gamma_shape,
187 | name='gamma_rr',
188 | initializer=self.gamma_diag_initializer,
189 | regularizer=self.gamma_diag_regularizer,
190 | constraint=self.gamma_diag_constraint
191 | )
192 |
193 | self.gamma_ri = self.add_weight(
194 | shape=gamma_shape,
195 | name='gamma_ri',
196 | initializer=self.gamma_off_initializer,
197 | regularizer=self.gamma_off_regularizer,
198 | constraint=self.gamma_off_constraint
199 | )
200 | self.gamma_rj = self.add_weight(
201 | shape=gamma_shape,
202 | name='gamma_rj',
203 | initializer=self.gamma_off_initializer,
204 | regularizer=self.gamma_off_regularizer,
205 | constraint=self.gamma_off_constraint
206 | )
207 | self.gamma_rk = self.add_weight(
208 | shape=gamma_shape,
209 | name='gamma_rk',
210 | initializer=self.gamma_off_initializer,
211 | regularizer=self.gamma_off_regularizer,
212 | constraint=self.gamma_off_constraint
213 | )
214 | self.gamma_ii = self.add_weight(
215 | shape=gamma_shape,
216 | name='gamma_ii',
217 | initializer=self.gamma_diag_initializer,
218 | regularizer=self.gamma_diag_regularizer,
219 | constraint=self.gamma_diag_constraint
220 | )
221 |
222 | self.gamma_ij = self.add_weight(
223 | shape=gamma_shape,
224 | name='gamma_ij',
225 | initializer=self.gamma_off_initializer,
226 | regularizer=self.gamma_off_regularizer,
227 | constraint=self.gamma_off_constraint
228 | )
229 | self.gamma_ik = self.add_weight(
230 | shape=gamma_shape,
231 | name='gamma_ik',
232 | initializer=self.gamma_off_initializer,
233 | regularizer=self.gamma_off_regularizer,
234 | constraint=self.gamma_off_constraint
235 | )
236 | self.gamma_jj = self.add_weight(
237 | shape=gamma_shape,
238 | name='gamma_jj',
239 | initializer=self.gamma_diag_initializer,
240 | regularizer=self.gamma_diag_regularizer,
241 | constraint=self.gamma_diag_constraint
242 | )
243 | self.gamma_jk = self.add_weight(
244 | shape=gamma_shape,
245 | name='gamma_jk',
246 | initializer=self.gamma_diag_initializer,
247 | regularizer=self.gamma_diag_regularizer,
248 | constraint=self.gamma_diag_constraint
249 | )
250 | self.gamma_kk = self.add_weight(
251 | shape=gamma_shape,
252 | name='gamma_kk',
253 | initializer=self.gamma_off_initializer,
254 | regularizer=self.gamma_off_regularizer,
255 | constraint=self.gamma_off_constraint
256 | )
257 | else:
258 | self.gamma_rr = None
259 | self.gamma_ri = None
260 | self.gamma_rj = None
261 | self.gamma_rk = None
262 | self.gamma_ii = None
263 | self.gamma_ij = None
264 | self.gamma_ik = None
265 | self.gamma_jj = None
266 | self.gamma_jk = None
267 | self.gamma_kk = None
268 |
269 |
270 | if self.use_bias:
271 | bias_shape = (4 * self.filters,)
272 | self.bias = self.add_weight(
273 | bias_shape,
274 | initializer=self.bias_initializer,
275 | name='bias',
276 | regularizer=self.bias_regularizer,
277 | constraint=self.bias_constraint
278 | )
279 |
280 | else:
281 | self.bias = None
282 |
283 | # Set input spec.
284 | self.input_spec = InputSpec(ndim=self.rank + 2,
285 | axes={channel_axis: input_dim * 4})
286 | self.built = True
287 |
288 | def call(self, inputs):
289 | channel_axis = 1 if self.data_format == 'channels_first' else -1
290 | input_dim = K.shape(inputs)[channel_axis] // 4
291 | index2 = self.filters*2
292 | index3 = self.filters*3
293 | if self.rank == 1:
294 | f_r = self.kernel[:, :, :self.filters]
295 | f_i = self.kernel[:, :, self.filters:index2]
296 | f_j = self.kernel[:, :, index2:index3]
297 | f_k = self.kernel[:, :, index3:]
298 | elif self.rank == 2:
299 | f_r = self.kernel[:, :, :, :self.filters]
300 | f_i = self.kernel[:, :, :, self.filters:index2]
301 | f_j = self.kernel[:, :, :, index2:index3]
302 | f_k = self.kernel[:, :, :, index3:]
303 | elif self.rank == 3:
304 | f_r = self.kernel[:, :, :, :, :self.filters]
305 | f_i = self.kernel[:, :, :, :, self.filters:index2]
306 | f_j = self.kernel[:, :, :, :, index2:index3]
307 | f_k = self.kernel[:, :, :, :, index3:]
308 |
309 | convArgs = {"strides": self.strides[0] if self.rank == 1 else self.strides,
310 | "padding": self.padding,
311 | "data_format": self.data_format,
312 | "dilation_rate": self.dilation_rate[0] if self.rank == 1 else self.dilation_rate}
313 | convFunc = {1: K.conv1d,
314 | 2: K.conv2d,
315 | 3: K.conv3d}[self.rank]
316 |
317 |
318 | #
319 | # Performing quaternion convolution
320 | #
321 |
322 | f_r._keras_shape = self.kernel_shape
323 | f_i._keras_shape = self.kernel_shape
324 | f_j._keras_shape = self.kernel_shape
325 | f_k._keras_shape = self.kernel_shape
326 |
327 | cat_kernels_4_r = K.concatenate([f_r, -f_i, -f_j, -f_k], axis=-2)
328 | cat_kernels_4_i = K.concatenate([f_i, f_r, -f_k, f_j], axis=-2)
329 | cat_kernels_4_j = K.concatenate([f_j, f_k, f_r, -f_i], axis=-2)
330 | cat_kernels_4_k = K.concatenate([f_k, -f_j, f_i, f_r], axis=-2)
331 | cat_kernels_4_quaternion = K.concatenate([cat_kernels_4_r, cat_kernels_4_i, cat_kernels_4_j, cat_kernels_4_k], axis=-1)
332 | cat_kernels_4_quaternion._keras_shape = self.kernel_size + (4 * input_dim, 4 * self.filters)
333 |
334 | output = convFunc(inputs, cat_kernels_4_quaternion, **convArgs)
335 |
336 | if self.use_bias:
337 | output = K.bias_add(
338 | output,
339 | self.bias,
340 | data_format=self.data_format
341 | )
342 | if self.activation is not None:
343 | output = self.activation(output)
344 |
345 | return output
346 |
347 | def compute_output_shape(self, input_shape):
348 | if self.data_format == 'channels_last':
349 | space = input_shape[1:-1]
350 | new_space = []
351 | for i in range(len(space)):
352 | new_dim = conv_utils.conv_output_length(
353 | space[i],
354 | self.kernel_size[i],
355 | padding=self.padding,
356 | stride=self.strides[i],
357 | dilation=self.dilation_rate[i]
358 | )
359 | new_space.append(new_dim)
360 | return (input_shape[0],) + tuple(new_space) + (4 * self.filters,)
361 | if self.data_format == 'channels_first':
362 | space = input_shape[2:]
363 | new_space = []
364 | for i in range(len(space)):
365 | new_dim = conv_utils.conv_output_length(
366 | space[i],
367 | self.kernel_size[i],
368 | padding=self.padding,
369 | stride=self.strides[i],
370 | dilation=self.dilation_rate[i])
371 | new_space.append(new_dim)
372 | return (input_shape[0],) + (4 * self.filters,) + tuple(new_space)
373 |
374 | def get_config(self):
375 | config = {
376 | 'rank': self.rank,
377 | 'filters': self.filters,
378 | 'kernel_size': self.kernel_size,
379 | 'strides': self.strides,
380 | 'padding': self.padding,
381 | 'data_format': self.data_format,
382 | 'dilation_rate': self.dilation_rate,
383 | 'activation': activations.serialize(self.activation),
384 | 'use_bias': self.use_bias,
385 | 'normalize_weight': self.normalize_weight,
386 | 'kernel_initializer': sanitizedInitSer(self.kernel_initializer),
387 | 'bias_initializer': sanitizedInitSer(self.bias_initializer),
388 | 'gamma_diag_initializer': sanitizedInitSer(self.gamma_diag_initializer),
389 | 'gamma_off_initializer': sanitizedInitSer(self.gamma_off_initializer),
390 | 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),
391 | 'bias_regularizer': regularizers.serialize(self.bias_regularizer),
392 | 'gamma_diag_regularizer': regularizers.serialize(self.gamma_diag_regularizer),
393 | 'gamma_off_regularizer': regularizers.serialize(self.gamma_off_regularizer),
394 | 'activity_regularizer': regularizers.serialize(self.activity_regularizer),
395 | 'kernel_constraint': constraints.serialize(self.kernel_constraint),
396 | 'bias_constraint': constraints.serialize(self.bias_constraint),
397 | 'gamma_diag_constraint': constraints.serialize(self.gamma_diag_constraint),
398 | 'gamma_off_constraint': constraints.serialize(self.gamma_off_constraint),
399 | 'init_criterion': self.init_criterion,
400 | 'spectral_parametrization': self.spectral_parametrization,
401 | }
402 | base_config = super(QuaternionConv, self).get_config()
403 | return dict(list(base_config.items()) + list(config.items()))
404 |
405 |
406 |
407 | class QuaternionConv1D(QuaternionConv):
408 | """1D quaternion convolution layer.
409 | This layer creates a quaternion convolution kernel that is convolved
410 | with a quaternion input layer over a single quaternion spatial (or temporal) dimension
411 | to produce a quaternion output tensor.
412 | If `use_bias` is True, a bias vector is created and added to the quaternion output.
413 | Finally, if `activation` is not `None`,
414 | it is applied each of the real and imaginary parts of the output.
415 | When using this layer as the first layer in a model,
416 | provide an `input_shape` argument
417 | (tuple of integers or `None`, e.g.
418 | `(10, 128)` for sequences of 10 vectors of 128-dimensional vectors,
419 | or `(None, 128)` for variable-length sequences of 128-dimensional vectors.
420 | # Arguments
421 | filters: Integer, the dimensionality of the output space, i.e,
422 | the number of quaternion feature maps. It is also the effective number
423 | of feature maps for each of the real and imaginary parts.
424 | (i.e. the number of quaternion filters in the convolution)
425 | The total effective number of filters is 2 x filters.
426 | kernel_size: An integer or tuple/list of n integers, specifying the
427 | dimensions of the convolution window.
428 | strides: An integer or tuple/list of a single integer,
429 | specifying the stride length of the convolution.
430 | Specifying any stride value != 1 is incompatible with specifying
431 | any `dilation_rate` value != 1.
432 | padding: One of `"valid"`, `"causal"` or `"same"` (case-insensitive).
433 | `"causal"` results in causal (dilated) convolutions, e.g. output[t]
434 | does not depend on input[t+1:]. Useful when modeling temporal data
435 | where the model should not violate the temporal order.
436 | See [WaveNet: A Generative Model for Raw Audio, section 2.1](https://arxiv.org/abs/1609.03499).
437 | dilation_rate: an integer or tuple/list of a single integer, specifying
438 | the dilation rate to use for dilated convolution.
439 | Currently, specifying any `dilation_rate` value != 1 is
440 | incompatible with specifying any `strides` value != 1.
441 | activation: Activation function to use
442 | (see keras.activations).
443 | If you don't specify anything, no activation is applied
444 | (ie. "linear" activation: `a(x) = x`).
445 | use_bias: Boolean, whether the layer uses a bias vector.
446 | normalize_weight: Boolean, whether the layer normalizes its quaternion
447 | weights before convolving the quaternion input.
448 | The quaternion normalization performed is similar to the one
449 | for the batchnorm. Each of the quaternion kernels are centred and multiplied by
450 | the inverse square root of covariance matrix.
451 | Then, a quaternion multiplication is perfromed as the normalized weights are
452 | multiplied by the quaternion scaling factor gamma.
453 | kernel_initializer: Initializer for the quaternion `kernel` weights matrix.
454 | By default it is 'quaternion'. The 'quaternion_independent'
455 | and the usual initializers could also be used.
456 | (see keras.initializers and init.py).
457 | bias_initializer: Initializer for the bias vector
458 | (see keras.initializers).
459 | kernel_regularizer: Regularizer function applied to
460 | the `kernel` weights matrix
461 | (see keras.regularizers).
462 | bias_regularizer: Regularizer function applied to the bias vector
463 | (see keras.regularizers).
464 | activity_regularizer: Regularizer function applied to
465 | the output of the layer (its "activation").
466 | (see keras.regularizers).
467 | kernel_constraint: Constraint function applied to the kernel matrix
468 | (see keras.constraints).
469 | bias_constraint: Constraint function applied to the bias vector
470 | (see keras.constraints).
471 | spectral_parametrization: Whether or not to use a spectral
472 | parametrization of the parameters.
473 | # Input shape
474 | 3D tensor with shape: `(batch_size, steps, input_dim)`
475 | # Output shape
476 | 3D tensor with shape: `(batch_size, new_steps, 2 x filters)`
477 | `steps` value might have changed due to padding or strides.
478 | """
479 |
480 | def __init__(self, filters,
481 | kernel_size,
482 | strides=1,
483 | padding='valid',
484 | data_format='channels_last',
485 | dilation_rate=1,
486 | activation=None,
487 | use_bias=True,
488 | kernel_initializer='quaternion',
489 | bias_initializer='zeros',
490 | kernel_regularizer=None,
491 | bias_regularizer=None,
492 | activity_regularizer=None,
493 | kernel_constraint=None,
494 | bias_constraint=None,
495 | seed=None,
496 | init_criterion='he',
497 | spectral_parametrization=False,
498 | **kwargs):
499 | super(QuaternionConv1D, self).__init__(
500 | rank=1,
501 | filters=filters,
502 | kernel_size=kernel_size,
503 | strides=strides,
504 | padding=padding,
505 | data_format=data_format,
506 | dilation_rate=dilation_rate,
507 | activation=activation,
508 | use_bias=use_bias,
509 | kernel_initializer=kernel_initializer,
510 | bias_initializer=bias_initializer,
511 | kernel_regularizer=kernel_regularizer,
512 | bias_regularizer=bias_regularizer,
513 | activity_regularizer=activity_regularizer,
514 | kernel_constraint=kernel_constraint,
515 | bias_constraint=bias_constraint,
516 | init_criterion=init_criterion,
517 | spectral_parametrization=spectral_parametrization,
518 | **kwargs)
519 |
520 | def get_config(self):
521 | config = super(QuaternionConv1D, self).get_config()
522 | config.pop('rank')
523 | config.pop('data_format')
524 | return config
525 |
526 |
527 | class QuaternionConv2D(QuaternionConv):
528 | """2D Quaternion convolution layer (e.g. spatial convolution over images).
529 | This layer creates a quaternion convolution kernel that is convolved
530 | with a quaternion input layer to produce a quaternion output tensor. If `use_bias`
531 | is True, a quaternion bias vector is created and added to the outputs.
532 | Finally, if `activation` is not `None`, it is applied to both the
533 | real and imaginary parts of the output.
534 | When using this layer as the first layer in a model,
535 | provide the keyword argument `input_shape`
536 | (tuple of integers, does not include the sample axis),
537 | e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures
538 | in `data_format="channels_last"`.
539 | # Arguments
540 | filters: Integer, the dimensionality of the quaternion output space
541 | (i.e, the number quaternion feature maps in the convolution).
542 | The total effective number of filters or feature maps is 2 x filters.
543 | kernel_size: An integer or tuple/list of 2 integers, specifying the
544 | width and height of the 2D convolution window.
545 | Can be a single integer to specify the same value for
546 | all spatial dimensions.
547 | strides: An integer or tuple/list of 2 integers,
548 | specifying the strides of the convolution along the width and height.
549 | Can be a single integer to specify the same value for
550 | all spatial dimensions.
551 | Specifying any stride value != 1 is incompatible with specifying
552 | any `dilation_rate` value != 1.
553 | padding: one of `"valid"` or `"same"` (case-insensitive).
554 | data_format: A string,
555 | one of `channels_last` (default) or `channels_first`.
556 | The ordering of the dimensions in the inputs.
557 | `channels_last` corresponds to inputs with shape
558 | `(batch, height, width, channels)` while `channels_first`
559 | corresponds to inputs with shape
560 | `(batch, channels, height, width)`.
561 | It defaults to the `image_data_format` value found in your
562 | Keras config file at `~/.keras/keras.json`.
563 | If you never set it, then it will be "channels_last".
564 | dilation_rate: an integer or tuple/list of 2 integers, specifying
565 | the dilation rate to use for dilated convolution.
566 | Can be a single integer to specify the same value for
567 | all spatial dimensions.
568 | Currently, specifying any `dilation_rate` value != 1 is
569 | incompatible with specifying any stride value != 1.
570 | activation: Activation function to use
571 | (see keras.activations).
572 | If you don't specify anything, no activation is applied
573 | (ie. "linear" activation: `a(x) = x`).
574 | use_bias: Boolean, whether the layer uses a bias vector.
575 | normalize_weight: Boolean, whether the layer normalizes its quaternion
576 | weights before convolving the quaternion input.
577 | The quaternion normalization performed is similar to the one
578 | for the batchnorm. Each of the quaternion kernels are centred and multiplied by
579 | the inverse square root of covariance matrix.
580 | Then, a quaternion multiplication is perfromed as the normalized weights are
581 | multiplied by the quaternion scaling factor gamma.
582 | kernel_initializer: Initializer for the quaternion `kernel` weights matrix.
583 | By default it is 'quaternion'. The 'quaternion_independent'
584 | and the usual initializers could also be used.
585 | (see keras.initializers and init.py).
586 | bias_initializer: Initializer for the bias vector
587 | (see keras.initializers).
588 | kernel_regularizer: Regularizer function applied to
589 | the `kernel` weights matrix
590 | (see keras.regularizers).
591 | bias_regularizer: Regularizer function applied to the bias vector
592 | (see keras.regularizers).
593 | activity_regularizer: Regularizer function applied to
594 | the output of the layer (its "activation").
595 | (see keras.regularizers).
596 | kernel_constraint: Constraint function applied to the kernel matrix
597 | (see keras.constraints).
598 | bias_constraint: Constraint function applied to the bias vector
599 | (see keras.constraints).
600 | spectral_parametrization: Whether or not to use a spectral
601 | parametrization of the parameters.
602 | # Input shape
603 | 4D tensor with shape:
604 | `(samples, channels, rows, cols)` if data_format='channels_first'
605 | or 4D tensor with shape:
606 | `(samples, rows, cols, channels)` if data_format='channels_last'.
607 | # Output shape
608 | 4D tensor with shape:
609 | `(samples, 2 x filters, new_rows, new_cols)` if data_format='channels_first'
610 | or 4D tensor with shape:
611 | `(samples, new_rows, new_cols, 2 x filters)` if data_format='channels_last'.
612 | `rows` and `cols` values might have changed due to padding.
613 | """
614 |
615 | def __init__(self, filters,
616 | kernel_size,
617 | strides=(1, 1),
618 | padding='valid',
619 | data_format='channels_last',
620 | dilation_rate=(1, 1),
621 | activation=None,
622 | use_bias=True,
623 | kernel_initializer='quaternion',
624 | bias_initializer='zeros',
625 | kernel_regularizer=None,
626 | bias_regularizer=None,
627 | activity_regularizer=None,
628 | kernel_constraint=None,
629 | bias_constraint=None,
630 | seed=None,
631 | init_criterion='he',
632 | spectral_parametrization=False,
633 | **kwargs):
634 | super(QuaternionConv2D, self).__init__(
635 | rank=2,
636 | filters=filters,
637 | kernel_size=kernel_size,
638 | strides=strides,
639 | padding=padding,
640 | data_format=data_format,
641 | dilation_rate=dilation_rate,
642 | activation=activation,
643 | use_bias=use_bias,
644 | kernel_initializer=kernel_initializer,
645 | bias_initializer=bias_initializer,
646 | kernel_regularizer=kernel_regularizer,
647 | bias_regularizer=bias_regularizer,
648 | activity_regularizer=activity_regularizer,
649 | kernel_constraint=kernel_constraint,
650 | bias_constraint=bias_constraint,
651 | init_criterion=init_criterion,
652 | spectral_parametrization=spectral_parametrization,
653 | **kwargs)
654 |
655 | def get_config(self):
656 | config = super(QuaternionConv2D, self).get_config()
657 | config.pop('rank')
658 | return config
659 |
660 |
661 | class QuaternionConv3D(QuaternionConv):
662 | """3D convolution layer (e.g. spatial convolution over volumes).
663 | This layer creates a quaternion convolution kernel that is convolved
664 | with a quaternion layer input to produce a quaternion output tensor.
665 | If `use_bias` is True,
666 | a quaternion bias vector is created and added to the outputs. Finally, if
667 | `activation` is not `None`, it is applied to each of the real and imaginary
668 | parts of the output.
669 | When using this layer as the first layer in a model,
670 | provide the keyword argument `input_shape`
671 | (tuple of integers, does not include the sample axis),
672 | e.g. `input_shape=(2, 128, 128, 128, 3)` for 128x128x128 volumes
673 | with 3 channels,
674 | in `data_format="channels_last"`.
675 | # Arguments
676 | filters: Integer, the dimensionality of the quaternion output space
677 | (i.e, the number quaternion feature maps in the convolution).
678 | The total effective number of filters or feature maps is 2 x filters.
679 | kernel_size: An integer or tuple/list of 3 integers, specifying the
680 | width and height of the 3D convolution window.
681 | Can be a single integer to specify the same value for
682 | all spatial dimensions.
683 | strides: An integer or tuple/list of 3 integers,
684 | specifying the strides of the convolution along each spatial dimension.
685 | Can be a single integer to specify the same value for
686 | all spatial dimensions.
687 | Specifying any stride value != 1 is incompatible with specifying
688 | any `dilation_rate` value != 1.
689 | padding: one of `"valid"` or `"same"` (case-insensitive).
690 | data_format: A string,
691 | one of `channels_last` (default) or `channels_first`.
692 | The ordering of the dimensions in the inputs.
693 | `channels_last` corresponds to inputs with shape
694 | `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`
695 | while `channels_first` corresponds to inputs with shape
696 | `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.
697 | It defaults to the `image_data_format` value found in your
698 | Keras config file at `~/.keras/keras.json`.
699 | If you never set it, then it will be "channels_last".
700 | dilation_rate: an integer or tuple/list of 3 integers, specifying
701 | the dilation rate to use for dilated convolution.
702 | Can be a single integer to specify the same value for
703 | all spatial dimensions.
704 | Currently, specifying any `dilation_rate` value != 1 is
705 | incompatible with specifying any stride value != 1.
706 | activation: Activation function to use
707 | (see keras.activations).
708 | If you don't specify anything, no activation is applied
709 | (ie. "linear" activation: `a(x) = x`).
710 | use_bias: Boolean, whether the layer uses a bias vector.
711 | normalize_weight: Boolean, whether the layer normalizes its quaternion
712 | weights before convolving the quaternion input.
713 | The quaternion normalization performed is similar to the one
714 | for the batchnorm. Each of the quaternion kernels are centred and multiplied by
715 | the inverse square root of covariance matrix.
716 | Then, a quaternion multiplication is perfromed as the normalized weights are
717 | multiplied by the quaternion scaling factor gamma.
718 | kernel_initializer: Initializer for the quaternion `kernel` weights matrix.
719 | By default it is 'quaternion'. The 'quaternion_independent'
720 | and the usual initializers could also be used.
721 | (see keras.initializers and init.py).
722 | bias_initializer: Initializer for the bias vector
723 | (see keras.initializers).
724 | kernel_regularizer: Regularizer function applied to
725 | the `kernel` weights matrix
726 | (see keras.regularizers).
727 | bias_regularizer: Regularizer function applied to the bias vector
728 | (see keras.regularizers).
729 | activity_regularizer: Regularizer function applied to
730 | the output of the layer (its "activation").
731 | (see keras.regularizers).
732 | kernel_constraint: Constraint function applied to the kernel matrix
733 | (see keras.constraints).
734 | bias_constraint: Constraint function applied to the bias vector
735 | (see keras.constraints).
736 | spectral_parametrization: Whether or not to use a spectral
737 | parametrization of the parameters.
738 | # Input shape
739 | 5D tensor with shape:
740 | `(samples, channels, conv_dim1, conv_dim2, conv_dim3)` if data_format='channels_first'
741 | or 5D tensor with shape:
742 | `(samples, conv_dim1, conv_dim2, conv_dim3, channels)` if data_format='channels_last'.
743 | # Output shape
744 | 5D tensor with shape:
745 | `(samples, 2 x filters, new_conv_dim1, new_conv_dim2, new_conv_dim3)` if data_format='channels_first'
746 | or 5D tensor with shape:
747 | `(samples, new_conv_dim1, new_conv_dim2, new_conv_dim3, 2 x filters)` if data_format='channels_last'.
748 | `new_conv_dim1`, `new_conv_dim2` and `new_conv_dim3` values might have changed due to padding.
749 | """
750 |
751 | def __init__(self, filters,
752 | kernel_size,
753 | strides=(1, 1, 1),
754 | padding='valid',
755 | data_format='channels_last',
756 | dilation_rate=(1, 1, 1),
757 | activation=None,
758 | use_bias=True,
759 | kernel_initializer='quaternion',
760 | bias_initializer='zeros',
761 | kernel_regularizer=None,
762 | bias_regularizer=None,
763 | activity_regularizer=None,
764 | kernel_constraint=None,
765 | bias_constraint=None,
766 | seed=None,
767 | init_criterion='he',
768 | spectral_parametrization=False,
769 | **kwargs):
770 | super(QuaternionConv3D, self).__init__(
771 | rank=3,
772 | filters=filters,
773 | kernel_size=kernel_size,
774 | strides=strides,
775 | padding=padding,
776 | data_format=data_format,
777 | dilation_rate=dilation_rate,
778 | activation=activation,
779 | use_bias=use_bias,
780 | kernel_initializer=kernel_initializer,
781 | bias_initializer=bias_initializer,
782 | kernel_regularizer=kernel_regularizer,
783 | bias_regularizer=bias_regularizer,
784 | activity_regularizer=activity_regularizer,
785 | kernel_constraint=kernel_constraint,
786 | bias_constraint=bias_constraint,
787 | init_criterion=init_criterion,
788 | spectral_parametrization=spectral_parametrization,
789 | **kwargs)
790 |
791 | def get_config(self):
792 | config = super(QuaternionConv3D, self).get_config()
793 | config.pop('rank')
794 | return config
795 |
796 | def sanitizedInitGet(init):
797 | if init in ["sqrt_init"]:
798 | return sqrt_init
799 | elif init in ["complex", "complex_independent",
800 | "glorot_complex", "he_complex",
801 | "quaternion", "quaternion_independent"]:
802 | return init
803 | else:
804 | return initializers.get(init)
805 |
806 | def sanitizedInitSer(init):
807 | if init in [sqrt_init]:
808 | return "sqrt_init"
809 | elif init == "quaternion" or isinstance(init, QuaternionInit):
810 | return "quaternion"
811 | elif init == "quaternion_independent" or isinstance(init, QuaternionIndependentFilters):
812 | return "quaternion_independent"
813 | else:
814 | return initializers.serialize(init)
815 |
816 |
817 | # Aliases
818 | QuaternionConvolution1D = QuaternionConv1D
819 | QuaternionConvolution2D = QuaternionConv2D
820 | QuaternionConvolution3D = QuaternionConv3D
821 |
--------------------------------------------------------------------------------