or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

activations.mdapplications.mdbackend-config.mdcore-framework.mdindex.mdinitializers.mdlayers.mdlosses-metrics.mdoperations.mdoptimizers.mdpreprocessing.mdregularizers.mdtraining-callbacks.md

core-framework.mddocs/

0

# Core Framework Classes

1

2

Essential classes and functions that form the foundation of Keras, including model containers, layer base classes, input handling, and core data structures for building neural networks.

3

4

## Capabilities

5

6

### Model Classes

7

8

High-level model containers that organize layers into trainable neural networks with built-in training, evaluation, and prediction capabilities.

9

10

```python { .api }

11

class Sequential:

12

"""

13

Linear stack of layers model.

14

15

Args:

16

layers (list, optional): List of layers to add to the model

17

name (str, optional): Name of the model

18

"""

19

def __init__(self, layers=None, name=None): ...

20

21

def add(self, layer):

22

"""Add a layer to the model."""

23

24

def compile(self, optimizer, loss=None, metrics=None, **kwargs):

25

"""Configure the model for training."""

26

27

def fit(self, x, y=None, batch_size=None, epochs=1, validation_data=None, **kwargs):

28

"""Train the model."""

29

30

def evaluate(self, x, y=None, batch_size=None, **kwargs):

31

"""Evaluate the model."""

32

33

def predict(self, x, batch_size=None, **kwargs):

34

"""Generate predictions."""

35

36

class Model:

37

"""

38

Functional API model for complex architectures.

39

40

Args:

41

inputs: Input tensor(s) or list of input tensors

42

outputs: Output tensor(s) or list of output tensors

43

name (str, optional): Name of the model

44

"""

45

def __init__(self, inputs, outputs, name=None): ...

46

47

def compile(self, optimizer, loss=None, metrics=None, **kwargs):

48

"""Configure the model for training."""

49

50

def fit(self, x, y=None, batch_size=None, epochs=1, validation_data=None, **kwargs):

51

"""Train the model."""

52

53

def evaluate(self, x, y=None, batch_size=None, **kwargs):

54

"""Evaluate the model."""

55

56

def predict(self, x, batch_size=None, **kwargs):

57

"""Generate predictions."""

58

59

def summary(self, line_length=None, positions=None, print_fn=None):

60

"""Print model architecture summary."""

61

```

62

63

### Base Layer Class

64

65

Foundation class for all neural network layers providing common functionality for parameter management, computation, and serialization.

66

67

```python { .api }

68

class Layer:

69

"""

70

Base class for all neural network layers.

71

72

Args:

73

trainable (bool): Whether layer weights should be updated during training

74

name (str, optional): Name of the layer

75

dtype (str, optional): Data type for layer computations

76

"""

77

def __init__(self, trainable=True, name=None, dtype=None, **kwargs): ...

78

79

def call(self, inputs, training=None, mask=None):

80

"""Forward pass computation (must be implemented by subclasses)."""

81

82

def build(self, input_shape):

83

"""Build layer parameters based on input shape."""

84

85

def add_weight(self, name, shape, dtype=None, initializer='zeros',

86

regularizer=None, trainable=None):

87

"""Add a weight variable to the layer."""

88

89

def get_weights(self):

90

"""Get layer weights as NumPy arrays."""

91

92

def set_weights(self, weights):

93

"""Set layer weights from NumPy arrays."""

94

95

def get_config(self):

96

"""Get layer configuration for serialization."""

97

```

98

99

### Input Handling

100

101

Functions and classes for defining model inputs with proper shape and type specifications.

102

103

```python { .api }

104

def Input(shape, batch_size=None, name=None, dtype=None, sparse=None):

105

"""

106

Create an input tensor for a Keras model.

107

108

Args:

109

shape (tuple): Shape of the input (excluding batch dimension)

110

batch_size (int, optional): Batch size

111

name (str, optional): Name of the input

112

dtype (str, optional): Data type

113

sparse (bool, optional): Whether input is sparse

114

115

Returns:

116

KerasTensor: Input tensor

117

"""

118

119

class InputSpec:

120

"""

121

Specification for layer inputs.

122

123

Args:

124

dtype (str, optional): Expected data type

125

shape (tuple, optional): Expected shape

126

ndim (int, optional): Expected number of dimensions

127

max_ndim (int, optional): Maximum number of dimensions

128

min_ndim (int, optional): Minimum number of dimensions

129

axes (dict, optional): Axes constraints

130

"""

131

def __init__(self, dtype=None, shape=None, ndim=None,

132

max_ndim=None, min_ndim=None, axes=None): ...

133

```

134

135

### Core Data Structures

136

137

Essential data structures for tensor operations and variable management in neural networks.

138

139

```python { .api }

140

class KerasTensor:

141

"""

142

Symbolic tensor for building computation graphs.

143

144

Attributes:

145

shape (tuple): Tensor shape

146

dtype (str): Data type

147

name (str): Tensor name

148

"""

149

shape: tuple

150

dtype: str

151

name: str

152

153

class Variable:

154

"""

155

Trainable variable that persists across calls.

156

157

Args:

158

initializer: Initial value or initializer function

159

shape (tuple, optional): Variable shape

160

dtype (str, optional): Data type

161

trainable (bool): Whether variable should be trained

162

name (str, optional): Variable name

163

"""

164

def __init__(self, initializer, shape=None, dtype=None,

165

trainable=True, name=None): ...

166

167

def assign(self, value):

168

"""Update variable value."""

169

170

def assign_add(self, delta):

171

"""Add delta to variable value."""

172

173

def assign_sub(self, delta):

174

"""Subtract delta from variable value."""

175

176

def numpy(self):

177

"""Get variable value as NumPy array."""

178

```

179

180

### Model Utilities

181

182

Utility functions for model construction, cloning, and serialization.

183

184

```python { .api }

185

def clone_model(model, input_tensors=None):

186

"""

187

Clone a Keras model.

188

189

Args:

190

model: Model to clone

191

input_tensors (list, optional): New input tensors

192

193

Returns:

194

Model: Cloned model

195

"""

196

197

def model_from_json(json_string, custom_objects=None):

198

"""

199

Load model architecture from JSON.

200

201

Args:

202

json_string (str): JSON string containing model config

203

custom_objects (dict, optional): Custom objects for deserialization

204

205

Returns:

206

Model: Reconstructed model

207

"""

208

```

209

210

## Usage Examples

211

212

### Building a Sequential Model

213

214

```python

215

import keras

216

from keras import layers

217

218

# Create and configure a sequential model

219

model = keras.Sequential([

220

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

221

layers.Dropout(0.2),

222

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

223

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

224

])

225

226

# Compile the model

227

model.compile(

228

optimizer='adam',

229

loss='sparse_categorical_crossentropy',

230

metrics=['accuracy']

231

)

232

233

# Display model architecture

234

model.summary()

235

```

236

237

### Building a Functional API Model

238

239

```python

240

import keras

241

from keras import layers

242

243

# Define inputs

244

inputs = keras.Input(shape=(28, 28, 1))

245

246

# Build the model graph

247

x = layers.Conv2D(32, 3, activation='relu')(inputs)

248

x = layers.MaxPooling2D(2)(x)

249

x = layers.Conv2D(64, 3, activation='relu')(x)

250

x = layers.MaxPooling2D(2)(x)

251

x = layers.Flatten()(x)

252

x = layers.Dense(64, activation='relu')(x)

253

outputs = layers.Dense(10, activation='softmax')(x)

254

255

# Create the model

256

model = keras.Model(inputs=inputs, outputs=outputs)

257

258

# Compile and train

259

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

260

model.fit(x_train, y_train, epochs=5, validation_data=(x_val, y_val))

261

```

262

263

### Custom Layer Development

264

265

```python

266

import keras

267

from keras import layers

268

269

class CustomDenseLayer(layers.Layer):

270

def __init__(self, units, activation=None, **kwargs):

271

super().__init__(**kwargs)

272

self.units = units

273

self.activation = keras.activations.get(activation)

274

275

def build(self, input_shape):

276

self.w = self.add_weight(

277

name='kernel',

278

shape=(input_shape[-1], self.units),

279

initializer='glorot_uniform',

280

trainable=True

281

)

282

self.b = self.add_weight(

283

name='bias',

284

shape=(self.units,),

285

initializer='zeros',

286

trainable=True

287

)

288

super().build(input_shape)

289

290

def call(self, inputs):

291

x = keras.ops.matmul(inputs, self.w) + self.b

292

return self.activation(x) if self.activation else x

293

294

def get_config(self):

295

config = super().get_config()

296

config.update({

297

'units': self.units,

298

'activation': keras.activations.serialize(self.activation)

299

})

300

return config

301

302

# Use the custom layer

303

model = keras.Sequential([

304

CustomDenseLayer(64, activation='relu', input_shape=(784,)),

305

CustomDenseLayer(10, activation='softmax')

306

])

307

```