0
# Builder Pattern
1
2
Advanced model construction using the builder pattern for fine-grained control over the import process. The ModelBuilder provides a fluent interface for configuring all aspects of model import.
3
4
## ModelBuilder Class
5
6
The `KerasModel.ModelBuilder` class provides a fluent API for constructing `KerasModel` and `KerasSequentialModel` instances with full control over configuration sources and import behavior.
7
8
```java { .api }
9
public static class ModelBuilder implements Cloneable {
10
public ModelBuilder modelJson(String modelJson);
11
public ModelBuilder modelJsonFilename(String modelJsonFilename) throws IOException;
12
public ModelBuilder modelJsonInputStream(InputStream modelJsonInputStream) throws IOException;
13
public ModelBuilder modelYaml(String modelYaml);
14
public ModelBuilder modelYamlFilename(String modelYamlFilename) throws IOException;
15
public ModelBuilder modelYamlInputStream(InputStream modelYamlInputStream) throws IOException;
16
public ModelBuilder modelHdf5Filename(String modelHdf5Filename)
17
throws UnsupportedKerasConfigurationException, InvalidKerasConfigurationException;
18
public ModelBuilder weightsHdf5Filename(String weightsHdf5Filename);
19
public ModelBuilder trainingJson(String trainingJson);
20
public ModelBuilder trainingJsonInputStream(InputStream trainingJsonInputStream) throws IOException;
21
public ModelBuilder enforceTrainingConfig(boolean enforceTrainingConfig);
22
public KerasModel buildModel()
23
throws IOException, InvalidKerasConfigurationException, UnsupportedKerasConfigurationException;
24
public KerasSequentialModel buildSequential()
25
throws IOException, InvalidKerasConfigurationException, UnsupportedKerasConfigurationException;
26
}
27
```
28
29
## Configuration Methods
30
31
### Model Configuration
32
33
Set the model architecture from various sources.
34
35
```java { .api }
36
// Set model configuration directly as JSON string
37
public ModelBuilder modelJson(String modelJson);
38
39
// Load model configuration from JSON file
40
public ModelBuilder modelJsonFilename(String modelJsonFilename) throws IOException;
41
42
// Load model configuration from InputStream
43
public ModelBuilder modelJsonInputStream(InputStream modelJsonInputStream) throws IOException;
44
45
// Set model configuration as YAML string
46
public ModelBuilder modelYaml(String modelYaml);
47
48
// Load model configuration from YAML file
49
public ModelBuilder modelYamlFilename(String modelYamlFilename) throws IOException;
50
51
// Load model configuration from YAML InputStream
52
public ModelBuilder modelYamlInputStream(InputStream modelYamlInputStream) throws IOException;
53
```
54
55
### Complete HDF5 Model
56
57
Load both configuration and weights from a single HDF5 file.
58
59
```java { .api }
60
// Load complete model from HDF5 file (configuration + weights + optional training config)
61
public ModelBuilder modelHdf5Filename(String modelHdf5Filename)
62
throws UnsupportedKerasConfigurationException, InvalidKerasConfigurationException;
63
```
64
65
### Weights Configuration
66
67
Set model weights from HDF5 files.
68
69
```java { .api }
70
// Set weights from separate HDF5 file
71
public ModelBuilder weightsHdf5Filename(String weightsHdf5Filename);
72
```
73
74
### Training Configuration
75
76
Set training-related configuration for complete model import.
77
78
```java { .api }
79
// Set training configuration directly as JSON string
80
public ModelBuilder trainingJson(String trainingJson);
81
82
// Load training configuration from InputStream
83
public ModelBuilder trainingJsonInputStream(InputStream trainingJsonInputStream) throws IOException;
84
```
85
86
### Import Behavior
87
88
Control how the import process handles unsupported configurations.
89
90
```java { .api }
91
// Set whether to enforce training configuration compatibility
92
public ModelBuilder enforceTrainingConfig(boolean enforceTrainingConfig);
93
```
94
95
## Build Methods
96
97
Create the final model instances from the configured builder.
98
99
```java { .api }
100
// Build Functional API model (KerasModel)
101
public KerasModel buildModel()
102
throws IOException, InvalidKerasConfigurationException, UnsupportedKerasConfigurationException;
103
104
// Build Sequential model (KerasSequentialModel)
105
public KerasSequentialModel buildSequential()
106
throws IOException, InvalidKerasConfigurationException, UnsupportedKerasConfigurationException;
107
```
108
109
## Usage Examples
110
111
### Basic Builder Usage
112
113
```java
114
import org.deeplearning4j.nn.modelimport.keras.KerasModel;
115
import org.deeplearning4j.nn.graph.ComputationGraph;
116
117
// Create builder and configure
118
KerasModel kerasModel = new KerasModel.ModelBuilder()
119
.modelJsonFilename("model_config.json")
120
.weightsHdf5Filename("model_weights.h5")
121
.enforceTrainingConfig(false)
122
.buildModel();
123
124
// Get DeepLearning4J model
125
ComputationGraph model = kerasModel.getComputationGraph();
126
```
127
128
### Sequential Model with Builder
129
130
```java
131
import org.deeplearning4j.nn.modelimport.keras.KerasSequentialModel;
132
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
133
134
// Build Sequential model
135
KerasSequentialModel kerasModel = new KerasModel.ModelBuilder()
136
.modelJsonFilename("sequential_config.json")
137
.weightsHdf5Filename("sequential_weights.h5")
138
.buildSequential();
139
140
// Get DeepLearning4J model
141
MultiLayerNetwork model = kerasModel.getMultiLayerNetwork();
142
```
143
144
### Complete HDF5 Import
145
146
```java
147
// Import complete model from single HDF5 file
148
KerasModel kerasModel = new KerasModel.ModelBuilder()
149
.modelHdf5Filename("complete_model.h5")
150
.enforceTrainingConfig(true)
151
.buildModel();
152
153
ComputationGraph model = kerasModel.getComputationGraph();
154
```
155
156
### From JSON String
157
158
```java
159
// Configure model from JSON string directly
160
String modelJson = "{'class_name': 'Sequential', 'config': [...]}";
161
162
KerasSequentialModel kerasModel = new KerasModel.ModelBuilder()
163
.modelJson(modelJson)
164
.buildSequential();
165
166
MultiLayerNetwork model = kerasModel.getMultiLayerNetwork();
167
```
168
169
### With Training Configuration
170
171
```java
172
// Include training configuration
173
KerasModel kerasModel = new KerasModel.ModelBuilder()
174
.modelJsonFilename("model.json")
175
.weightsHdf5Filename("weights.h5")
176
.trainingJson("{'loss': 'categorical_crossentropy', 'optimizer': 'adam'}")
177
.enforceTrainingConfig(true)
178
.buildModel();
179
```
180
181
### From InputStreams
182
183
```java
184
import java.io.FileInputStream;
185
186
// Load from InputStreams (useful for resources or network streams)
187
try (FileInputStream modelStream = new FileInputStream("model.json");
188
FileInputStream trainingStream = new FileInputStream("training.json")) {
189
190
KerasModel kerasModel = new KerasModel.ModelBuilder()
191
.modelJsonInputStream(modelStream)
192
.trainingJsonInputStream(trainingStream)
193
.weightsHdf5Filename("weights.h5")
194
.buildModel();
195
196
ComputationGraph model = kerasModel.getComputationGraph();
197
}
198
```
199
200
### YAML Configuration Support
201
202
```java
203
// Use YAML configuration instead of JSON
204
KerasModel kerasModel = new KerasModel.ModelBuilder()
205
.modelYamlFilename("model_config.yaml")
206
.weightsHdf5Filename("weights.h5")
207
.buildModel();
208
```
209
210
## Advanced Patterns
211
212
### Configuration Validation
213
214
```java
215
// Build configuration-only model first for validation
216
KerasModel kerasModel = new KerasModel.ModelBuilder()
217
.modelJsonFilename("model.json")
218
.enforceTrainingConfig(true)
219
.buildModel();
220
221
// Validate configuration
222
ComputationGraphConfiguration config = kerasModel.getComputationGraphConfiguration();
223
System.out.println("Model has " + config.getVertices().size() + " layers");
224
225
// Then load with weights
226
kerasModel = new KerasModel.ModelBuilder()
227
.modelJsonFilename("model.json")
228
.weightsHdf5Filename("weights.h5")
229
.enforceTrainingConfig(false) // Relax enforcement for weights loading
230
.buildModel();
231
```
232
233
### Multiple Weight Files
234
235
```java
236
// Load architecture once, use with different weight files
237
KerasModel.ModelBuilder baseBuilder = new KerasModel.ModelBuilder()
238
.modelJsonFilename("shared_architecture.json")
239
.enforceTrainingConfig(false);
240
241
// Model with weights v1
242
ComputationGraph modelV1 = baseBuilder
243
.weightsHdf5Filename("weights_v1.h5")
244
.buildModel()
245
.getComputationGraph();
246
247
// Model with weights v2
248
ComputationGraph modelV2 = baseBuilder
249
.weightsHdf5Filename("weights_v2.h5")
250
.buildModel()
251
.getComputationGraph();
252
```
253
254
### Error Handling with Builder
255
256
```java
257
try {
258
KerasModel kerasModel = new KerasModel.ModelBuilder()
259
.modelJsonFilename("model.json")
260
.weightsHdf5Filename("weights.h5")
261
.enforceTrainingConfig(true)
262
.buildModel();
263
264
ComputationGraph model = kerasModel.getComputationGraph();
265
266
} catch (IOException e) {
267
System.err.println("File I/O error: " + e.getMessage());
268
} catch (InvalidKerasConfigurationException e) {
269
System.err.println("Invalid configuration: " + e.getMessage());
270
} catch (UnsupportedKerasConfigurationException e) {
271
System.err.println("Unsupported feature: " + e.getMessage());
272
273
// Retry with relaxed enforcement
274
KerasModel kerasModel = new KerasModel.ModelBuilder()
275
.modelJsonFilename("model.json")
276
.weightsHdf5Filename("weights.h5")
277
.enforceTrainingConfig(false)
278
.buildModel();
279
}
280
```
281
282
## Builder vs Static Methods
283
284
### When to Use Builder Pattern
285
286
- **Complex Configuration**: Multiple configuration sources (JSON + YAML + training config)
287
- **Fine-grained Control**: Need specific control over enforcement and validation
288
- **Reusable Configuration**: Same builder configuration used multiple times
289
- **Stream-based Input**: Loading from InputStreams or network sources
290
- **Error Recovery**: Need to retry with different settings
291
292
### When to Use Static Methods
293
294
- **Simple Import**: Single HDF5 file or JSON+weights combination
295
- **Quick Prototyping**: Fast model loading for testing
296
- **Standard Workflows**: Common import patterns without special requirements
297
298
```java
299
// Simple case - use static method
300
ComputationGraph simple = KerasModelImport.importKerasModelAndWeights("model.h5");
301
302
// Complex case - use builder
303
KerasModel complex = new KerasModel.ModelBuilder()
304
.modelYamlFilename("architecture.yaml")
305
.weightsHdf5Filename("weights.h5")
306
.trainingJsonInputStream(trainingStream)
307
.enforceTrainingConfig(false)
308
.buildModel();
309
```
310
311
## Builder State Management
312
313
The `ModelBuilder` implements `Cloneable` for creating copies with shared configuration:
314
315
```java
316
// Create base configuration
317
KerasModel.ModelBuilder baseBuilder = new KerasModel.ModelBuilder()
318
.modelJsonFilename("base_architecture.json")
319
.enforceTrainingConfig(false);
320
321
// Clone and customize for different use cases
322
KerasModel.ModelBuilder trainBuilder = baseBuilder.clone()
323
.weightsHdf5Filename("initial_weights.h5");
324
325
KerasModel.ModelBuilder inferenceBuilder = baseBuilder.clone()
326
.weightsHdf5Filename("trained_weights.h5");
327
```