MCPcopy Create free account
hub / github.com/Kaggle/docker-python / TestKeras

Class TestKeras

tests/test_keras.py:10–73  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8import keras
9
10class TestKeras(unittest.TestCase):
11 def test_train(self):
12 path = '/input/tests/data/mnist.npz'
13 with np.load(path) as f:
14 x_train, y_train = f['x_train'], f['y_train']
15 x_test, y_test = f['x_test'], f['y_test']
16
17
18 # Scale images to the [0, 1] range
19 x_train = x_train.astype("float32") / 255
20 x_train = x_train[:100, :]
21 y_train = y_train[:100]
22 x_test = x_test.astype("float32") / 255
23 x_test = x_test[:100, :]
24 y_test = y_test[:100]
25 # Make sure images have shape (28, 28, 1)
26 x_train = np.expand_dims(x_train, -1)
27 x_test = np.expand_dims(x_test, -1)
28
29 # Model parameters
30 num_classes = 10
31 input_shape = (28, 28, 1)
32
33 model = keras.Sequential(
34 [
35 keras.layers.Input(shape=input_shape),
36 keras.layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
37 keras.layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
38 keras.layers.MaxPooling2D(pool_size=(2, 2)),
39 keras.layers.Conv2D(128, kernel_size=(3, 3), activation="relu"),
40 keras.layers.Conv2D(128, kernel_size=(3, 3), activation="relu"),
41 keras.layers.GlobalAveragePooling2D(),
42 keras.layers.Dropout(0.5),
43 keras.layers.Dense(num_classes, activation="softmax"),
44 ]
45 )
46
47 model.compile(
48 loss=keras.losses.SparseCategoricalCrossentropy(),
49 optimizer=keras.optimizers.Adam(learning_rate=1e-3),
50 metrics=[
51 keras.metrics.SparseCategoricalAccuracy(name="acc"),
52 ],
53 )
54
55 batch_size = 128
56 epochs = 1
57
58 callbacks = [
59 keras.callbacks.ModelCheckpoint(filepath="model_at_epoch_{epoch}.keras"), # Saves model checkpoint while training
60 keras.callbacks.EarlyStopping(monitor="val_loss", patience=2),
61 ]
62
63 model.fit(
64 x_train,
65 y_train,
66 batch_size=batch_size,
67 epochs=epochs,

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected