text stringlengths 0 4.99k |
|---|
model = build_model() |
model.summary() |
Model: \"handwriting_recognizer\" |
__________________________________________________________________________________________________ |
Layer (type) Output Shape Param # Connected to |
================================================================================================== |
image (InputLayer) [(None, 128, 32, 1)] 0 |
__________________________________________________________________________________________________ |
Conv1 (Conv2D) (None, 128, 32, 32) 320 image[0][0] |
__________________________________________________________________________________________________ |
pool1 (MaxPooling2D) (None, 64, 16, 32) 0 Conv1[0][0] |
__________________________________________________________________________________________________ |
Conv2 (Conv2D) (None, 64, 16, 64) 18496 pool1[0][0] |
__________________________________________________________________________________________________ |
pool2 (MaxPooling2D) (None, 32, 8, 64) 0 Conv2[0][0] |
__________________________________________________________________________________________________ |
reshape (Reshape) (None, 32, 512) 0 pool2[0][0] |
__________________________________________________________________________________________________ |
dense1 (Dense) (None, 32, 64) 32832 reshape[0][0] |
__________________________________________________________________________________________________ |
dropout (Dropout) (None, 32, 64) 0 dense1[0][0] |
__________________________________________________________________________________________________ |
bidirectional (Bidirectional) (None, 32, 256) 197632 dropout[0][0] |
__________________________________________________________________________________________________ |
bidirectional_1 (Bidirectional) (None, 32, 128) 164352 bidirectional[0][0] |
__________________________________________________________________________________________________ |
label (InputLayer) [(None, None)] 0 |
__________________________________________________________________________________________________ |
dense2 (Dense) (None, 32, 81) 10449 bidirectional_1[0][0] |
__________________________________________________________________________________________________ |
ctc_loss (CTCLayer) (None, 32, 81) 0 label[0][0] |
dense2[0][0] |
================================================================================================== |
Total params: 424,081 |
Trainable params: 424,081 |
Non-trainable params: 0 |
__________________________________________________________________________________________________ |
Evaluation metric |
Edit Distance is the most widely used metric for evaluating OCR models. In this section, we will implement it and use it as a callback to monitor our model. |
We first segregate the validation images and their labels for convenience. |
validation_images = [] |
validation_labels = [] |
for batch in validation_ds: |
validation_images.append(batch[\"image\"]) |
validation_labels.append(batch[\"label\"]) |
Now, we create a callback to monitor the edit distances. |
def calculate_edit_distance(labels, predictions): |
# Get a single batch and convert its labels to sparse tensors. |
saprse_labels = tf.cast(tf.sparse.from_dense(labels), dtype=tf.int64) |
# Make predictions and convert them to sparse tensors. |
input_len = np.ones(predictions.shape[0]) * predictions.shape[1] |
predictions_decoded = keras.backend.ctc_decode( |
predictions, input_length=input_len, greedy=True |
)[0][0][:, :max_len] |
sparse_predictions = tf.cast( |
tf.sparse.from_dense(predictions_decoded), dtype=tf.int64 |
) |
# Compute individual edit distances and average them out. |
edit_distances = tf.edit_distance( |
sparse_predictions, saprse_labels, normalize=False |
) |
return tf.reduce_mean(edit_distances) |
class EditDistanceCallback(keras.callbacks.Callback): |
def __init__(self, pred_model): |
super().__init__() |
self.prediction_model = pred_model |
def on_epoch_end(self, epoch, logs=None): |
edit_distances = [] |
for i in range(len(validation_images)): |
labels = validation_labels[i] |
predictions = self.prediction_model.predict(validation_images[i]) |
edit_distances.append(calculate_edit_distance(labels, predictions).numpy()) |
print( |
f\"Mean edit distance for epoch {epoch + 1}: {np.mean(edit_distances):.4f}\" |
) |
Training |
Now we are ready to kick off model training. |
epochs = 10 # To get good results this should be at least 50. |
model = build_model() |
prediction_model = keras.models.Model( |
model.get_layer(name=\"image\").input, model.get_layer(name=\"dense2\").output |
) |
edit_distance_callback = EditDistanceCallback(prediction_model) |
# Train the model. |
history = model.fit( |
train_ds, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.