09.05.2023 Views

pdfcoffee

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5

predictions = tf.keras.layers.Dense(LABEL_DIMENSIONS,

activation='softmax')(x)

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

model.summary()

Compile it:

optimizer = tf.keras.optimizers.SGD()

model.compile(loss='categorical_crossentropy',

optimizer=optimizer,

metrics=['accuracy'])

Define a strategy, which is None for now because we run on CPUs first:

strategy = None

#strategy = tf.distribute.MirroredStrategy()

config = tf.estimator.RunConfig(train_distribute=strategy)

Now let's convert the tf.keras model into a convenient Estimator:

estimator = tf.keras.estimator.model_to_estimator(model,

config=config)

The next step is to define input functions for training and for testing, which is pretty

easy if we use tf.data:

def input_fn(images, labels, epochs, batch_size):

# Convert the inputs to a Dataset

dataset = tf.data.Dataset.from_tensor_slices((images, labels))

# Shuffle, repeat, and batch the examples.

SHUFFLE_SIZE = 5000

dataset = dataset.shuffle(SHUFFLE_SIZE).repeat(epochs).

batch(batch_size)

dataset = dataset.prefetch(None)

# Return the dataset.

return dataset

We are ready to start the training with the following code:

BATCH_SIZE = 512

EPOCHS = 50

estimator_train_result = estimator.train(input_fn=lambda:input_

fn(train_images, train_labels,

epochs=EPOCHS,

batch_size=BATCH_SIZE))

print(estimator_train_result)

[ 149 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!