text stringlengths 0 4.99k |
|---|
plt.figure(figsize=(4, 4)) |
for i, patch in enumerate(patches[0]): |
ax = plt.subplot(n, n, i + 1) |
patch_img = tf.reshape(patch, (patch_size, patch_size, 3)) |
plt.imshow(patch_img.numpy().astype(\"uint8\")) |
plt.axis(\"off\") |
Image size: 72 X 72 |
Patch size: 6 X 6 |
Patches per image: 144 |
Elements per patch: 108 |
png |
png |
Implement the patch encoding layer |
The PatchEncoder layer will linearly transform a patch by projecting it into a vector of size projection_dim. In addition, it adds a learnable position embedding to the projected vector. |
class PatchEncoder(layers.Layer): |
def __init__(self, num_patches, projection_dim): |
super(PatchEncoder, self).__init__() |
self.num_patches = num_patches |
self.projection = layers.Dense(units=projection_dim) |
self.position_embedding = layers.Embedding( |
input_dim=num_patches, output_dim=projection_dim |
) |
def call(self, patch): |
positions = tf.range(start=0, limit=self.num_patches, delta=1) |
encoded = self.projection(patch) + self.position_embedding(positions) |
return encoded |
Build the ViT model |
The ViT model consists of multiple Transformer blocks, which use the layers.MultiHeadAttention layer as a self-attention mechanism applied to the sequence of patches. The Transformer blocks produce a [batch_size, num_patches, projection_dim] tensor, which is processed via an classifier head with softmax to produce the ... |
Unlike the technique described in the paper, which prepends a learnable embedding to the sequence of encoded patches to serve as the image representation, all the outputs of the final Transformer block are reshaped with layers.Flatten() and used as the image representation input to the classifier head. Note that the la... |
def create_vit_classifier(): |
inputs = layers.Input(shape=input_shape) |
# Augment data. |
augmented = data_augmentation(inputs) |
# Create patches. |
patches = Patches(patch_size)(augmented) |
# Encode patches. |
encoded_patches = PatchEncoder(num_patches, projection_dim)(patches) |
# Create multiple layers of the Transformer block. |
for _ in range(transformer_layers): |
# Layer normalization 1. |
x1 = layers.LayerNormalization(epsilon=1e-6)(encoded_patches) |
# Create a multi-head attention layer. |
attention_output = layers.MultiHeadAttention( |
num_heads=num_heads, key_dim=projection_dim, dropout=0.1 |
)(x1, x1) |
# Skip connection 1. |
x2 = layers.Add()([attention_output, encoded_patches]) |
# Layer normalization 2. |
x3 = layers.LayerNormalization(epsilon=1e-6)(x2) |
# MLP. |
x3 = mlp(x3, hidden_units=transformer_units, dropout_rate=0.1) |
# Skip connection 2. |
encoded_patches = layers.Add()([x3, x2]) |
# Create a [batch_size, projection_dim] tensor. |
representation = layers.LayerNormalization(epsilon=1e-6)(encoded_patches) |
representation = layers.Flatten()(representation) |
representation = layers.Dropout(0.5)(representation) |
# Add MLP. |
features = mlp(representation, hidden_units=mlp_head_units, dropout_rate=0.5) |
# Classify outputs. |
logits = layers.Dense(num_classes)(features) |
# Create the Keras model. |
model = keras.Model(inputs=inputs, outputs=logits) |
return model |
Compile, train, and evaluate the mode |
def run_experiment(model): |
optimizer = tfa.optimizers.AdamW( |
learning_rate=learning_rate, weight_decay=weight_decay |
) |
model.compile( |
optimizer=optimizer, |
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), |
metrics=[ |
keras.metrics.SparseCategoricalAccuracy(name=\"accuracy\"), |
keras.metrics.SparseTopKCategoricalAccuracy(5, name=\"top-5-accuracy\"), |
], |
) |
checkpoint_filepath = \"/tmp/checkpoint\" |
checkpoint_callback = keras.callbacks.ModelCheckpoint( |
checkpoint_filepath, |
monitor=\"val_accuracy\", |
save_best_only=True, |
save_weights_only=True, |
) |
history = model.fit( |
x=x_train, |
y=y_train, |
batch_size=batch_size, |
epochs=num_epochs, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.