or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

activations.mdapplications.mddata-utils.mdindex.mdinitializers.mdlayers.mdmodels.mdoperations.mdrandom.mdregularizers.mdsaving.mdtraining.md

saving.mddocs/

0

# Model Saving and Serialization

1

2

Keras provides comprehensive functionality for saving and loading models and weights, along with serialization utilities for custom objects and configurations.

3

4

## Capabilities

5

6

### Model Persistence

7

8

Core functions for saving and loading complete models including architecture, weights, and training configuration.

9

10

```python { .api }

11

def save_model(model, filepath, overwrite=True, save_format=None, **kwargs):

12

"""

13

Save a model to a file.

14

15

Parameters:

16

- model: Keras model instance to save

17

- filepath: Path where to save the model

18

- overwrite: Whether to overwrite existing file (default: True)

19

- save_format: Format to save in ('keras', 'h5', or 'tf') (default: None)

20

- **kwargs: Additional arguments for specific formats

21

22

Returns:

23

None

24

"""

25

26

def load_model(filepath, custom_objects=None, compile=True, safe_mode=True):

27

"""

28

Load a model from a file.

29

30

Parameters:

31

- filepath: Path to the saved model file

32

- custom_objects: Optional dict mapping names to custom classes/functions

33

- compile: Whether to compile the model after loading (default: True)

34

- safe_mode: Whether to load in safe mode (default: True)

35

36

Returns:

37

Keras model instance

38

"""

39

```

40

41

### Weight Management

42

43

Functions for saving and loading only the weights of a model without the architecture.

44

45

```python { .api }

46

def save_weights(model, filepath, overwrite=True, save_format=None, **kwargs):

47

"""

48

Save model weights to a file.

49

50

Parameters:

51

- model: Keras model instance

52

- filepath: Path where to save the weights

53

- overwrite: Whether to overwrite existing file (default: True)

54

- save_format: Format to save in ('keras', 'h5', or 'tf') (default: None)

55

- **kwargs: Additional arguments for specific formats

56

57

Returns:

58

None

59

"""

60

61

def load_weights(model, filepath, skip_mismatch=False, by_name=False, **kwargs):

62

"""

63

Load model weights from a file.

64

65

Parameters:

66

- model: Keras model instance to load weights into

67

- filepath: Path to the saved weights file

68

- skip_mismatch: Whether to skip mismatched layers (default: False)

69

- by_name: Whether to load weights by layer name (default: False)

70

- **kwargs: Additional arguments for specific formats

71

72

Returns:

73

None

74

"""

75

```

76

77

### Object Registration and Serialization

78

79

System for registering and managing custom objects for serialization compatibility.

80

81

```python { .api }

82

def register_keras_serializable(package='Custom', name=None):

83

"""

84

Decorator to register a class/function for Keras serialization.

85

86

Parameters:

87

- package: Package name for the registered object (default: 'Custom')

88

- name: Name to register object under (default: class/function name)

89

90

Returns:

91

Decorator function

92

"""

93

94

def get_custom_objects():

95

"""

96

Get the current custom object registry.

97

98

Returns:

99

Dict mapping names to custom objects

100

"""

101

102

def get_registered_name(obj):

103

"""

104

Get the registered name for a Keras object.

105

106

Parameters:

107

- obj: Object to get registered name for

108

109

Returns:

110

String name or None if not registered

111

"""

112

113

def get_registered_object(name, custom_objects=None, module_objects=None):

114

"""

115

Get a registered object by name.

116

117

Parameters:

118

- name: Name of the registered object

119

- custom_objects: Optional custom object dict

120

- module_objects: Optional module object dict

121

122

Returns:

123

The registered object

124

"""

125

126

class CustomObjectScope:

127

"""

128

Context manager for providing custom objects during deserialization.

129

130

Usage:

131

```python

132

with CustomObjectScope({'custom_fn': my_custom_function}):

133

model = keras.saving.load_model('my_model.keras')

134

```

135

"""

136

def __init__(self, custom_objects):

137

"""

138

Initialize the custom object scope.

139

140

Parameters:

141

- custom_objects: Dict mapping names to custom objects

142

"""

143

144

def __enter__(self):

145

"""Enter the context manager."""

146

147

def __exit__(self, *args):

148

"""Exit the context manager."""

149

150

def custom_object_scope(custom_objects):

151

"""

152

Create a custom object scope context manager.

153

154

Parameters:

155

- custom_objects: Dict mapping names to custom objects

156

157

Returns:

158

CustomObjectScope instance

159

"""

160

```

161

162

### Keras Object Serialization

163

164

Low-level serialization utilities for Keras objects and configurations.

165

166

```python { .api }

167

def serialize_keras_object(obj):

168

"""

169

Serialize a Keras object to a JSON-compatible dict.

170

171

Parameters:

172

- obj: Keras object to serialize

173

174

Returns:

175

Dict representation of the object

176

"""

177

178

def deserialize_keras_object(config, custom_objects=None, **kwargs):

179

"""

180

Deserialize a Keras object from a config dict.

181

182

Parameters:

183

- config: Dict configuration of the object

184

- custom_objects: Optional dict of custom objects

185

- **kwargs: Additional arguments for deserialization

186

187

Returns:

188

Deserialized Keras object

189

"""

190

```

191

192

### File Editing Utilities

193

194

Tools for editing saved Keras model files without full loading.

195

196

```python { .api }

197

class KerasFileEditor:

198

"""

199

Utility for editing Keras model files without full loading.

200

201

Usage:

202

```python

203

editor = KerasFileEditor('model.keras')

204

editor.inspect() # View model structure

205

editor.close()

206

```

207

"""

208

def __init__(self, filepath):

209

"""

210

Initialize the file editor.

211

212

Parameters:

213

- filepath: Path to the Keras model file

214

"""

215

216

def inspect(self):

217

"""

218

Inspect the model structure without loading.

219

220

Returns:

221

Dict with model information

222

"""

223

224

def close(self):

225

"""Close the file editor."""

226

```

227

228

## Usage Examples

229

230

### Basic Model Saving and Loading

231

232

```python

233

import keras

234

from keras import saving

235

236

# Create and train a model

237

model = keras.Sequential([

238

keras.layers.Dense(64, activation='relu', input_shape=(784,)),

239

keras.layers.Dense(10, activation='softmax')

240

])

241

242

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')

243

244

# Save the complete model

245

saving.save_model(model, 'my_model.keras')

246

247

# Load the model

248

loaded_model = saving.load_model('my_model.keras')

249

250

# Save only weights

251

saving.save_weights(model, 'my_weights.weights.h5')

252

253

# Load weights into existing model

254

new_model = keras.Sequential([

255

keras.layers.Dense(64, activation='relu', input_shape=(784,)),

256

keras.layers.Dense(10, activation='softmax')

257

])

258

saving.load_weights(new_model, 'my_weights.weights.h5')

259

```

260

261

### Custom Objects

262

263

```python

264

import keras

265

from keras import saving

266

267

@saving.register_keras_serializable()

268

def custom_activation(x):

269

return keras.ops.tanh(x) * 0.5

270

271

# Use custom activation in model

272

model = keras.Sequential([

273

keras.layers.Dense(64, activation=custom_activation),

274

keras.layers.Dense(10, activation='softmax')

275

])

276

277

# Save model with custom objects

278

saving.save_model(model, 'model_with_custom.keras')

279

280

# Load with custom object scope

281

with saving.CustomObjectScope({'custom_activation': custom_activation}):

282

loaded_model = saving.load_model('model_with_custom.keras')

283

284

# Or register globally

285

custom_objects = saving.get_custom_objects()

286

custom_objects['my_custom_activation'] = custom_activation

287

```

288

289

### Serialization Utilities

290

291

```python

292

import keras

293

from keras import saving

294

295

# Serialize a layer

296

layer = keras.layers.Dense(64, activation='relu')

297

config = saving.serialize_keras_object(layer)

298

299

# Deserialize the layer

300

new_layer = saving.deserialize_keras_object(config)

301

302

# File inspection

303

editor = saving.KerasFileEditor('my_model.keras')

304

info = editor.inspect()

305

print(info)

306

editor.close()

307

```

308

309

## File Formats

310

311

Keras supports multiple saving formats:

312

313

- **`.keras`**: Native Keras format (recommended)

314

- **`.h5`**: HDF5 format for compatibility

315

- **`.pb`**: TensorFlow SavedModel format

316

317

The native `.keras` format is recommended for new projects as it provides the most comprehensive support for all Keras features.