/
KerasLocallyConnected1D.java
181 lines (160 loc) · 8.25 KB
/
KerasLocallyConnected1D.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.deeplearning4j.nn.modelimport.keras.layers.local;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.nn.modelimport.keras.exceptions.InvalidKerasConfigurationException;
import org.deeplearning4j.nn.modelimport.keras.exceptions.UnsupportedKerasConfigurationException;
import org.deeplearning4j.nn.modelimport.keras.layers.convolutional.KerasConvolution;
import org.deeplearning4j.nn.modelimport.keras.utils.KerasActivationUtils;
import org.deeplearning4j.nn.api.layers.LayerConstraint;
import org.deeplearning4j.nn.conf.InputPreProcessor;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.deeplearning4j.nn.conf.layers.LocallyConnected1D;
import org.deeplearning4j.nn.modelimport.keras.utils.KerasConstraintUtils;
import org.deeplearning4j.nn.modelimport.keras.utils.KerasInitilizationUtils;
import org.deeplearning4j.nn.modelimport.keras.utils.KerasLayerUtils;
import org.deeplearning4j.nn.params.ConvolutionParamInitializer;
import org.deeplearning4j.nn.weights.IWeightInit;
import org.nd4j.linalg.api.ndarray.INDArray;
import java.util.HashMap;
import java.util.Map;
import static org.deeplearning4j.nn.modelimport.keras.layers.convolutional.KerasConvolutionUtils.*;
@Slf4j
@Data
@EqualsAndHashCode(callSuper = false)
public class KerasLocallyConnected1D extends KerasConvolution {
/**
* Pass-through constructor from KerasLayer
*
* @param kerasVersion major keras version
* @throws UnsupportedKerasConfigurationException Unsupported Keras config
*/
public KerasLocallyConnected1D(Integer kerasVersion) throws UnsupportedKerasConfigurationException {
super(kerasVersion);
}
/**
* Constructor from parsed Keras layer configuration dictionary.
*
* @param layerConfig dictionary containing Keras layer configuration
* @throws InvalidKerasConfigurationException Invalid Keras config
* @throws UnsupportedKerasConfigurationException Unsupported Keras config
*/
public KerasLocallyConnected1D(Map<String, Object> layerConfig)
throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException {
this(layerConfig, true);
}
/**
* Constructor from parsed Keras layer configuration dictionary.
*
* @param layerConfig dictionary containing Keras layer configuration
* @param enforceTrainingConfig whether to enforce training-related configuration options
* @throws InvalidKerasConfigurationException Invalid Keras config
* @throws UnsupportedKerasConfigurationException Unsupported Keras config
*/
public KerasLocallyConnected1D(Map<String, Object> layerConfig, boolean enforceTrainingConfig)
throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException {
super(layerConfig, enforceTrainingConfig);
hasBias = KerasLayerUtils.getHasBiasFromConfig(layerConfig, conf);
numTrainableParams = hasBias ? 2 : 1;
int[] dilationRate = getDilationRate(layerConfig, 1, conf, false);
IWeightInit init = KerasInitilizationUtils.getWeightInitFromConfig(layerConfig, conf.getLAYER_FIELD_INIT(),
enforceTrainingConfig, conf, kerasMajorVersion);
LayerConstraint biasConstraint = KerasConstraintUtils.getConstraintsFromConfig(
layerConfig, conf.getLAYER_FIELD_B_CONSTRAINT(), conf, kerasMajorVersion);
LayerConstraint weightConstraint = KerasConstraintUtils.getConstraintsFromConfig(
layerConfig, conf.getLAYER_FIELD_W_CONSTRAINT(), conf, kerasMajorVersion);
LocallyConnected1D.Builder builder = new LocallyConnected1D.Builder().name(this.layerName)
.nOut(KerasLayerUtils.getNOutFromConfig(layerConfig, conf)).dropOut(this.dropout)
.activation(KerasActivationUtils.getActivationFromConfig(layerConfig, conf))
.weightInit(conf.getKERAS_PARAM_NAME_W(), init)
.l1(this.weightL1Regularization).l2(this.weightL2Regularization)
.convolutionMode(getConvolutionModeFromConfig(layerConfig, conf))
.kernelSize(getKernelSizeFromConfig(layerConfig, 1, conf, kerasMajorVersion)[0])
.hasBias(hasBias)
.stride(getStrideFromConfig(layerConfig, 1, conf)[0]);
int[] padding = getPaddingFromBorderModeConfig(layerConfig, 1, conf, kerasMajorVersion);
if (padding != null)
builder.padding(padding[0]);
if (dilationRate != null)
builder.dilation(dilationRate[0]);
if (biasConstraint != null)
builder.constrainBias(biasConstraint);
if (weightConstraint != null)
builder.constrainWeights(weightConstraint);
this.layer = builder.build();
}
/**
* Get DL4J LocallyConnected1D layer.
*
* @return Locally connected 1D layer.
*/
public LocallyConnected1D getLocallyConnected1DLayer() {
return (LocallyConnected1D) this.layer;
}
/**
* Get layer output type.
*
* @param inputType Array of InputTypes
* @return output type as InputType
* @throws InvalidKerasConfigurationException Invalid Keras config
*/
@Override
public InputType getOutputType(InputType... inputType) throws InvalidKerasConfigurationException {
if (inputType.length > 1)
throw new InvalidKerasConfigurationException(
"Keras Convolution layer accepts only one input (received " + inputType.length + ")");
InputType.InputTypeRecurrent rnnType = (InputType.InputTypeRecurrent) inputType[0];
// Override input/output shape and input channels dynamically. This works since getOutputType will always
// be called when initializing the model.
((LocallyConnected1D) this.layer).setInputSize((int) rnnType.getTimeSeriesLength());
((LocallyConnected1D) this.layer).setNIn(rnnType.getSize());
((LocallyConnected1D) this.layer).computeOutputSize();
InputPreProcessor preprocessor = getInputPreprocessor(inputType[0]);
if (preprocessor != null) {
return this.getLocallyConnected1DLayer().getOutputType(-1, preprocessor.getOutputType(inputType[0]));
}
return this.getLocallyConnected1DLayer().getOutputType(-1, inputType[0]);
}
/**
* Set weights for 1D locally connected layer.
*
* @param weights Map from parameter name to INDArray.
*/
@Override
public void setWeights(Map<String, INDArray> weights) throws InvalidKerasConfigurationException {
this.weights = new HashMap<>();
if (weights.containsKey(conf.getKERAS_PARAM_NAME_W())) {
INDArray kerasParamValue = weights.get(conf.getKERAS_PARAM_NAME_W());
this.weights.put(ConvolutionParamInitializer.WEIGHT_KEY, kerasParamValue);
} else
throw new InvalidKerasConfigurationException(
"Parameter " + conf.getKERAS_PARAM_NAME_W() + " does not exist in weights");
if (hasBias) {
if (weights.containsKey(conf.getKERAS_PARAM_NAME_B()))
this.weights.put(ConvolutionParamInitializer.BIAS_KEY, weights.get(conf.getKERAS_PARAM_NAME_B()));
else
throw new InvalidKerasConfigurationException(
"Parameter " + conf.getKERAS_PARAM_NAME_B() + " does not exist in weights");
}
KerasLayerUtils.removeDefaultWeights(weights, conf);
}
}