Halaman ini diterjemahkan oleh Cloud Translation API.
Switch to English

Keterangan gambar dengan perhatian visual

Lihat di TensorFlow.org Jalankan di Google Colab Lihat sumber di GitHub Unduh buku catatan

Diberikan gambar seperti contoh di bawah ini, tujuan kami adalah menghasilkan teks seperti "peselancar mengendarai ombak".

Man Surfing

Sumber Gambar ; Lisensi: Domain Publik

Untuk mencapai ini, Anda akan menggunakan model berbasis perhatian, yang memungkinkan kita untuk melihat bagian gambar mana yang menjadi fokus model saat menghasilkan keterangan.

Ramalan

Arsitektur modelnya mirip dengan Show, Attend and Tell: Neural Image Caption Generation dengan Visual Attention .

Notebook ini adalah contoh ujung ke ujung. Saat Anda menjalankan notebook, ia mendownload set data MS-COCO , memproses dan menyimpan subset gambar menggunakan Inception V3, melatih model encoder-decoder, dan membuat teks pada gambar baru menggunakan model yang terlatih.

Dalam contoh ini, Anda akan melatih model pada jumlah data yang relatif kecil — 30.000 teks pertama untuk sekitar 20.000 gambar (karena ada beberapa teks per gambar dalam kumpulan data).

import tensorflow as tf

# You'll generate plots of attention in order to see which parts of an image
# our model focuses on during captioning
import matplotlib.pyplot as plt

# Scikit-learn includes many helpful utilities
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle

import re
import numpy as np
import os
import time
import json
from glob import glob
from PIL import Image
import pickle
.dll

Unduh dan siapkan dataset MS-COCO

Anda akan menggunakan kumpulan data MS-COCO untuk melatih model kami. Kumpulan data berisi lebih dari 82.000 gambar, yang masing-masing memiliki setidaknya 5 anotasi teks berbeda. Kode di bawah mengunduh dan mengekstrak kumpulan data secara otomatis.

# Download caption annotation files
annotation_folder = '/annotations/'
if not os.path.exists(os.path.abspath('.') + annotation_folder):
  annotation_zip = tf.keras.utils.get_file('captions.zip',
                                          cache_subdir=os.path.abspath('.'),
                                          origin = 'http://images.cocodataset.org/annotations/annotations_trainval2014.zip',
                                          extract = True)
  annotation_file = os.path.dirname(annotation_zip)+'/annotations/captions_train2014.json'
  os.remove(annotation_zip)

# Download image files
image_folder = '/train2014/'
if not os.path.exists(os.path.abspath('.') + image_folder):
  image_zip = tf.keras.utils.get_file('train2014.zip',
                                      cache_subdir=os.path.abspath('.'),
                                      origin = 'http://images.cocodataset.org/zips/train2014.zip',
                                      extract = True)
  PATH = os.path.dirname(image_zip) + image_folder
  os.remove(image_zip)
else:
  PATH = os.path.abspath('.') + image_folder
Downloading data from http://images.cocodataset.org/annotations/annotations_trainval2014.zip
252878848/252872794 [==============================] - 16s 0us/step
Downloading data from http://images.cocodataset.org/zips/train2014.zip
13510574080/13510573713 [==============================] - 787s 0us/step

Opsional: batasi ukuran set pelatihan

Untuk mempercepat pelatihan untuk tutorial ini, Anda akan menggunakan subset dari 30.000 teks dan gambarnya yang sesuai untuk melatih model kita. Memilih untuk menggunakan lebih banyak data akan menghasilkan kualitas teks yang lebih baik.

# Read the json file
with open(annotation_file, 'r') as f:
    annotations = json.load(f)

# Store captions and image names in vectors
all_captions = []
all_img_name_vector = []

for annot in annotations['annotations']:
    caption = '<start> ' + annot['caption'] + ' <end>'
    image_id = annot['image_id']
    full_coco_image_path = PATH + 'COCO_train2014_' + '%012d.jpg' % (image_id)

    all_img_name_vector.append(full_coco_image_path)
    all_captions.append(caption)

# Shuffle captions and image_names together
# Set a random state
train_captions, img_name_vector = shuffle(all_captions,
                                          all_img_name_vector,
                                          random_state=1)

# Select the first 30000 captions from the shuffled set
num_examples = 30000
train_captions = train_captions[:num_examples]
img_name_vector = img_name_vector[:num_examples]
len(train_captions), len(all_captions)
(30000, 414113)

Proses praproses gambar menggunakan InceptionV3

Selanjutnya, Anda akan menggunakan InceptionV3 (yang telah dilatih sebelumnya di Imagenet) untuk mengklasifikasikan setiap gambar. Anda akan mengekstrak fitur dari lapisan konvolusional terakhir.

Pertama, Anda akan mengonversi gambar ke dalam format yang diharapkan InceptionV3 dengan:

  • Mengubah ukuran gambar menjadi 299px kali 299px
  • Proses praproses gambar menggunakan metode preprocess_input untuk menormalkan gambar sehingga berisi piksel dalam rentang -1 hingga 1, yang cocok dengan format gambar yang digunakan untuk melatih InceptionV3.
def load_image(image_path):
    img = tf.io.read_file(image_path)
    img = tf.image.decode_jpeg(img, channels=3)
    img = tf.image.resize(img, (299, 299))
    img = tf.keras.applications.inception_v3.preprocess_input(img)
    return img, image_path

Inisialisasi InceptionV3 dan muat bobot Imagenet yang telah dilatih sebelumnya

Sekarang Anda akan membuat model tf.keras di mana lapisan keluaran adalah lapisan konvolusional terakhir dalam arsitektur InceptionV3. Bentuk keluaran dari lapisan ini adalah 8x8x2048 . Anda menggunakan lapisan konvolusional terakhir karena Anda menggunakan perhatian dalam contoh ini. Anda tidak melakukan inisialisasi ini selama pelatihan karena dapat menjadi penghambat.

  • Anda meneruskan setiap gambar melalui jaringan dan menyimpan vektor yang dihasilkan dalam kamus (image_name -> feature_vector).
  • Setelah semua gambar melewati jaringan, Anda membuat acar kamus dan menyimpannya ke disk.
image_model = tf.keras.applications.InceptionV3(include_top=False,
                                                weights='imagenet')
new_input = image_model.input
hidden_layer = image_model.layers[-1].output

image_features_extract_model = tf.keras.Model(new_input, hidden_layer)
Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/inception_v3/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5
87916544/87910968 [==============================] - 2s 0us/step

Caching fitur yang diekstrak dari InceptionV3

Anda akan memproses terlebih dahulu setiap gambar dengan InceptionV3 dan menyimpan output ke cache. Meng-cache output dalam RAM akan lebih cepat tetapi juga membutuhkan banyak memori, membutuhkan 8 * 8 * 2048 float per gambar. Pada saat penulisan, ini melebihi batasan memori Colab (saat ini memori 12GB).

Performa dapat ditingkatkan dengan strategi caching yang lebih canggih (misalnya, dengan memecah gambar untuk mengurangi I / O disk akses acak), tetapi itu akan membutuhkan lebih banyak kode.

Caching membutuhkan waktu sekitar 10 menit untuk dijalankan di Colab dengan GPU. Jika Anda ingin melihat bilah kemajuan, Anda dapat:

  1. instal tqdm :

    !pip install -q tqdm

  2. Impor tqdm:

    from tqdm import tqdm

  3. Ubah baris berikut:

    for img, path in image_dataset:

    untuk:

    for img, path in tqdm(image_dataset):

# Get unique images
encode_train = sorted(set(img_name_vector))

# Feel free to change batch_size according to your system configuration
image_dataset = tf.data.Dataset.from_tensor_slices(encode_train)
image_dataset = image_dataset.map(
  load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE).batch(16)

for img, path in image_dataset:
  batch_features = image_features_extract_model(img)
  batch_features = tf.reshape(batch_features,
                              (batch_features.shape[0], -1, batch_features.shape[3]))

  for bf, p in zip(batch_features, path):
    path_of_feature = p.numpy().decode("utf-8")
    np.save(path_of_feature, bf.numpy())

Proses praproses dan tokenize teks

  • Pertama, Anda akan memberi token pada teks (misalnya, dengan membagi spasi). Ini memberi kita kosakata dari semua kata unik dalam data (misalnya, "berselancar", "sepak bola", dan sebagainya).
  • Selanjutnya, Anda akan membatasi ukuran kosakata hingga 5.000 kata teratas (untuk menghemat memori). Anda akan mengganti semua kata lain dengan token "UNK" (tidak diketahui).
  • Anda kemudian membuat pemetaan kata-ke-indeks dan indeks-ke-kata.
  • Terakhir, Anda memasukkan semua urutan agar memiliki panjang yang sama dengan yang terpanjang.
# Find the maximum length of any caption in our dataset
def calc_max_length(tensor):
    return max(len(t) for t in tensor)
# Choose the top 5000 words from the vocabulary
top_k = 5000
tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=top_k,
                                                  oov_token="<unk>",
                                                  filters='!"#$%&()*+.,-/:;=?@[\]^_`{|}~ ')
tokenizer.fit_on_texts(train_captions)
train_seqs = tokenizer.texts_to_sequences(train_captions)
tokenizer.word_index['<pad>'] = 0
tokenizer.index_word[0] = '<pad>'
# Create the tokenized vectors
train_seqs = tokenizer.texts_to_sequences(train_captions)
# Pad each vector to the max_length of the captions
# If you do not provide a max_length value, pad_sequences calculates it automatically
cap_vector = tf.keras.preprocessing.sequence.pad_sequences(train_seqs, padding='post')
# Calculates the max_length, which is used to store the attention weights
max_length = calc_max_length(train_seqs)

Pisahkan data menjadi pelatihan dan pengujian

# Create training and validation sets using an 80-20 split
img_name_train, img_name_val, cap_train, cap_val = train_test_split(img_name_vector,
                                                                    cap_vector,
                                                                    test_size=0.2,
                                                                    random_state=0)
len(img_name_train), len(cap_train), len(img_name_val), len(cap_val)
(24000, 24000, 6000, 6000)

Buat set data tf.data untuk pelatihan

Gambar dan keterangan kami sudah siap! Selanjutnya, mari buat set data tf.data yang akan digunakan untuk melatih model kita.

# Feel free to change these parameters according to your system's configuration

BATCH_SIZE = 64
BUFFER_SIZE = 1000
embedding_dim = 256
units = 512
vocab_size = top_k + 1
num_steps = len(img_name_train) // BATCH_SIZE
# Shape of the vector extracted from InceptionV3 is (64, 2048)
# These two variables represent that vector shape
features_shape = 2048
attention_features_shape = 64
# Load the numpy files
def map_func(img_name, cap):
  img_tensor = np.load(img_name.decode('utf-8')+'.npy')
  return img_tensor, cap
dataset = tf.data.Dataset.from_tensor_slices((img_name_train, cap_train))

# Use map to load the numpy files in parallel
dataset = dataset.map(lambda item1, item2: tf.numpy_function(
          map_func, [item1, item2], [tf.float32, tf.int32]),
          num_parallel_calls=tf.data.experimental.AUTOTUNE)

# Shuffle and batch
dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)

Model

Fakta menarik: dekoder di bawah ini identik dengan yang ada di contoh Neural Machine Translation with Attention .

Arsitektur model terinspirasi oleh makalah Show, Attend and Tell .

  • Dalam contoh ini, Anda mengekstrak fitur dari lapisan konvolusional bawah InceptionV3 yang memberi kita bentuk vektor (8, 8, 2048).
  • Anda menekannya menjadi bentuk (64, 2048).
  • Vektor ini kemudian dilewatkan melalui Encoder CNN (yang terdiri dari satu lapisan yang terhubung sepenuhnya).
  • RNN (di sini GRU) hadir di atas gambar untuk memprediksi kata berikutnya.
class BahdanauAttention(tf.keras.Model):
  def __init__(self, units):
    super(BahdanauAttention, self).__init__()
    self.W1 = tf.keras.layers.Dense(units)
    self.W2 = tf.keras.layers.Dense(units)
    self.V = tf.keras.layers.Dense(1)

  def call(self, features, hidden):
    # features(CNN_encoder output) shape == (batch_size, 64, embedding_dim)

    # hidden shape == (batch_size, hidden_size)
    # hidden_with_time_axis shape == (batch_size, 1, hidden_size)
    hidden_with_time_axis = tf.expand_dims(hidden, 1)

    # attention_hidden_layer shape == (batch_size, 64, units)
    attention_hidden_layer = (tf.nn.tanh(self.W1(features) +
                                         self.W2(hidden_with_time_axis)))

    # score shape == (batch_size, 64, 1)
    # This gives you an unnormalized score for each image feature.
    score = self.V(attention_hidden_layer)

    # attention_weights shape == (batch_size, 64, 1)
    attention_weights = tf.nn.softmax(score, axis=1)

    # context_vector shape after sum == (batch_size, hidden_size)
    context_vector = attention_weights * features
    context_vector = tf.reduce_sum(context_vector, axis=1)

    return context_vector, attention_weights
class CNN_Encoder(tf.keras.Model):
    # Since you have already extracted the features and dumped it using pickle
    # This encoder passes those features through a Fully connected layer
    def __init__(self, embedding_dim):
        super(CNN_Encoder, self).__init__()
        # shape after fc == (batch_size, 64, embedding_dim)
        self.fc = tf.keras.layers.Dense(embedding_dim)

    def call(self, x):
        x = self.fc(x)
        x = tf.nn.relu(x)
        return x
class RNN_Decoder(tf.keras.Model):
  def __init__(self, embedding_dim, units, vocab_size):
    super(RNN_Decoder, self).__init__()
    self.units = units

    self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
    self.gru = tf.keras.layers.GRU(self.units,
                                   return_sequences=True,
                                   return_state=True,
                                   recurrent_initializer='glorot_uniform')
    self.fc1 = tf.keras.layers.Dense(self.units)
    self.fc2 = tf.keras.layers.Dense(vocab_size)

    self.attention = BahdanauAttention(self.units)

  def call(self, x, features, hidden):
    # defining attention as a separate model
    context_vector, attention_weights = self.attention(features, hidden)

    # x shape after passing through embedding == (batch_size, 1, embedding_dim)
    x = self.embedding(x)

    # x shape after concatenation == (batch_size, 1, embedding_dim + hidden_size)
    x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)

    # passing the concatenated vector to the GRU
    output, state = self.gru(x)

    # shape == (batch_size, max_length, hidden_size)
    x = self.fc1(output)

    # x shape == (batch_size * max_length, hidden_size)
    x = tf.reshape(x, (-1, x.shape[2]))

    # output shape == (batch_size * max_length, vocab)
    x = self.fc2(x)

    return x, state, attention_weights

  def reset_state(self, batch_size):
    return tf.zeros((batch_size, self.units))
encoder = CNN_Encoder(embedding_dim)
decoder = RNN_Decoder(embedding_dim, units, vocab_size)
optimizer = tf.keras.optimizers.Adam()
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(
    from_logits=True, reduction='none')

def loss_function(real, pred):
  mask = tf.math.logical_not(tf.math.equal(real, 0))
  loss_ = loss_object(real, pred)

  mask = tf.cast(mask, dtype=loss_.dtype)
  loss_ *= mask

  return tf.reduce_mean(loss_)

Pos pemeriksaan

checkpoint_path = "./checkpoints/train"
ckpt = tf.train.Checkpoint(encoder=encoder,
                           decoder=decoder,
                           optimizer = optimizer)
ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)
start_epoch = 0
if ckpt_manager.latest_checkpoint:
  start_epoch = int(ckpt_manager.latest_checkpoint.split('-')[-1])
  # restoring the latest checkpoint in checkpoint_path
  ckpt.restore(ckpt_manager.latest_checkpoint)

Latihan

  • Anda mengekstrak fitur yang disimpan dalam file .npy masing-masing dan kemudian meneruskan fitur tersebut melalui encoder.
  • Output encoder, status tersembunyi (diinisialisasi ke 0) dan input decoder (yang merupakan token awal) diteruskan ke decoder.
  • Dekoder mengembalikan prediksi dan status tersembunyi dekoder.
  • Status tersembunyi decoder kemudian diteruskan kembali ke model dan prediksi digunakan untuk menghitung kerugian.
  • Gunakan pemaksaan guru untuk memutuskan masukan berikutnya ke decoder.
  • Pemaksaan guru adalah teknik di mana kata target diteruskan sebagai masukan berikutnya ke decoder.
  • Langkah terakhir adalah menghitung gradien dan menerapkannya ke pengoptimal dan backpropagate.
# adding this in a separate cell because if you run the training cell
# many times, the loss_plot array will be reset
loss_plot = []
@tf.function
def train_step(img_tensor, target):
  loss = 0

  # initializing the hidden state for each batch
  # because the captions are not related from image to image
  hidden = decoder.reset_state(batch_size=target.shape[0])

  dec_input = tf.expand_dims([tokenizer.word_index['<start>']] * target.shape[0], 1)

  with tf.GradientTape() as tape:
      features = encoder(img_tensor)

      for i in range(1, target.shape[1]):
          # passing the features through the decoder
          predictions, hidden, _ = decoder(dec_input, features, hidden)

          loss += loss_function(target[:, i], predictions)

          # using teacher forcing
          dec_input = tf.expand_dims(target[:, i], 1)

  total_loss = (loss / int(target.shape[1]))

  trainable_variables = encoder.trainable_variables + decoder.trainable_variables

  gradients = tape.gradient(loss, trainable_variables)

  optimizer.apply_gradients(zip(gradients, trainable_variables))

  return loss, total_loss
EPOCHS = 20

for epoch in range(start_epoch, EPOCHS):
    start = time.time()
    total_loss = 0

    for (batch, (img_tensor, target)) in enumerate(dataset):
        batch_loss, t_loss = train_step(img_tensor, target)
        total_loss += t_loss

        if batch % 100 == 0:
            print ('Epoch {} Batch {} Loss {:.4f}'.format(
              epoch + 1, batch, batch_loss.numpy() / int(target.shape[1])))
    # storing the epoch end loss value to plot later
    loss_plot.append(total_loss / num_steps)

    if epoch % 5 == 0:
      ckpt_manager.save()

    print ('Epoch {} Loss {:.6f}'.format(epoch + 1,
                                         total_loss/num_steps))
    print ('Time taken for 1 epoch {} sec\n'.format(time.time() - start))
Epoch 1 Batch 0 Loss 2.0256
Epoch 1 Batch 100 Loss 1.0767
Epoch 1 Batch 200 Loss 0.9904
Epoch 1 Batch 300 Loss 0.8514
Epoch 1 Loss 1.035708
Time taken for 1 epoch 80.1693012714386 sec

Epoch 2 Batch 0 Loss 0.8047
Epoch 2 Batch 100 Loss 0.8696
Epoch 2 Batch 200 Loss 0.8090
Epoch 2 Batch 300 Loss 0.7596
Epoch 2 Loss 0.792247
Time taken for 1 epoch 37.58015012741089 sec

Epoch 3 Batch 0 Loss 0.8046
Epoch 3 Batch 100 Loss 0.7656
Epoch 3 Batch 200 Loss 0.7077
Epoch 3 Batch 300 Loss 0.6922
Epoch 3 Loss 0.723338
Time taken for 1 epoch 37.68060636520386 sec

Epoch 4 Batch 0 Loss 0.7137
Epoch 4 Batch 100 Loss 0.7308
Epoch 4 Batch 200 Loss 0.6677
Epoch 4 Batch 300 Loss 0.6926
Epoch 4 Loss 0.679668
Time taken for 1 epoch 37.798078298568726 sec

Epoch 5 Batch 0 Loss 0.6856
Epoch 5 Batch 100 Loss 0.6833
Epoch 5 Batch 200 Loss 0.6265
Epoch 5 Batch 300 Loss 0.6854
Epoch 5 Loss 0.644473
Time taken for 1 epoch 37.53870892524719 sec

Epoch 6 Batch 0 Loss 0.6272
Epoch 6 Batch 100 Loss 0.6874
Epoch 6 Batch 200 Loss 0.5755
Epoch 6 Batch 300 Loss 0.7087
Epoch 6 Loss 0.613456
Time taken for 1 epoch 37.658682107925415 sec

Epoch 7 Batch 0 Loss 0.6183
Epoch 7 Batch 100 Loss 0.6688
Epoch 7 Batch 200 Loss 0.5818
Epoch 7 Batch 300 Loss 0.5499
Epoch 7 Loss 0.584454
Time taken for 1 epoch 37.779391288757324 sec

Epoch 8 Batch 0 Loss 0.5725
Epoch 8 Batch 100 Loss 0.5993
Epoch 8 Batch 200 Loss 0.4813
Epoch 8 Batch 300 Loss 0.5400
Epoch 8 Loss 0.557220
Time taken for 1 epoch 37.670920610427856 sec

Epoch 9 Batch 0 Loss 0.5315
Epoch 9 Batch 100 Loss 0.5684
Epoch 9 Batch 200 Loss 0.4836
Epoch 9 Batch 300 Loss 0.5019
Epoch 9 Loss 0.530330
Time taken for 1 epoch 38.1601185798645 sec

Epoch 10 Batch 0 Loss 0.5405
Epoch 10 Batch 100 Loss 0.5402
Epoch 10 Batch 200 Loss 0.4997
Epoch 10 Batch 300 Loss 0.4807
Epoch 10 Loss 0.503714
Time taken for 1 epoch 37.68390440940857 sec

Epoch 11 Batch 0 Loss 0.4911
Epoch 11 Batch 100 Loss 0.4674
Epoch 11 Batch 200 Loss 0.4687
Epoch 11 Batch 300 Loss 0.4511
Epoch 11 Loss 0.477244
Time taken for 1 epoch 37.828065395355225 sec

Epoch 12 Batch 0 Loss 0.4636
Epoch 12 Batch 100 Loss 0.4855
Epoch 12 Batch 200 Loss 0.4708
Epoch 12 Batch 300 Loss 0.3912
Epoch 12 Loss 0.450926
Time taken for 1 epoch 37.86421489715576 sec

Epoch 13 Batch 0 Loss 0.4395
Epoch 13 Batch 100 Loss 0.4245
Epoch 13 Batch 200 Loss 0.4839
Epoch 13 Batch 300 Loss 0.4292
Epoch 13 Loss 0.426043
Time taken for 1 epoch 37.768298625946045 sec

Epoch 14 Batch 0 Loss 0.4486
Epoch 14 Batch 100 Loss 0.3647
Epoch 14 Batch 200 Loss 0.4102
Epoch 14 Batch 300 Loss 0.4379
Epoch 14 Loss 0.400702
Time taken for 1 epoch 37.78010821342468 sec

Epoch 15 Batch 0 Loss 0.4021
Epoch 15 Batch 100 Loss 0.4026
Epoch 15 Batch 200 Loss 0.3531
Epoch 15 Batch 300 Loss 0.3736
Epoch 15 Loss 0.379577
Time taken for 1 epoch 37.77936053276062 sec

Epoch 16 Batch 0 Loss 0.3497
Epoch 16 Batch 100 Loss 0.3565
Epoch 16 Batch 200 Loss 0.3530
Epoch 16 Batch 300 Loss 0.3145
Epoch 16 Loss 0.356853
Time taken for 1 epoch 37.956844329833984 sec

Epoch 17 Batch 0 Loss 0.3651
Epoch 17 Batch 100 Loss 0.3703
Epoch 17 Batch 200 Loss 0.3086
Epoch 17 Batch 300 Loss 0.3552
Epoch 17 Loss 0.335187
Time taken for 1 epoch 38.11415076255798 sec

Epoch 18 Batch 0 Loss 0.3213
Epoch 18 Batch 100 Loss 0.3022
Epoch 18 Batch 200 Loss 0.3396
Epoch 18 Batch 300 Loss 0.3026
Epoch 18 Loss 0.315363
Time taken for 1 epoch 37.959665060043335 sec

Epoch 19 Batch 0 Loss 0.3075
Epoch 19 Batch 100 Loss 0.2823
Epoch 19 Batch 200 Loss 0.2825
Epoch 19 Batch 300 Loss 0.3005
Epoch 19 Loss 0.298387
Time taken for 1 epoch 37.6931517124176 sec

Epoch 20 Batch 0 Loss 0.3203
Epoch 20 Batch 100 Loss 0.2769
Epoch 20 Batch 200 Loss 0.2925
Epoch 20 Batch 300 Loss 0.2624
Epoch 20 Loss 0.282723
Time taken for 1 epoch 37.898409605026245 sec


plt.plot(loss_plot)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Loss Plot')
plt.show()

png

Caption!

  • Fungsi evaluasi mirip dengan loop pelatihan, kecuali Anda tidak menggunakan pengajar yang memaksa di sini. Masukan ke decoder pada setiap langkah waktu adalah prediksi sebelumnya bersama dengan status tersembunyi dan keluaran encoder.
  • Berhenti memprediksi saat model memprediksi token akhir.
  • Dan simpan bobot perhatian untuk setiap langkah waktu.
def evaluate(image):
    attention_plot = np.zeros((max_length, attention_features_shape))

    hidden = decoder.reset_state(batch_size=1)

    temp_input = tf.expand_dims(load_image(image)[0], 0)
    img_tensor_val = image_features_extract_model(temp_input)
    img_tensor_val = tf.reshape(img_tensor_val, (img_tensor_val.shape[0], -1, img_tensor_val.shape[3]))

    features = encoder(img_tensor_val)

    dec_input = tf.expand_dims([tokenizer.word_index['<start>']], 0)
    result = []

    for i in range(max_length):
        predictions, hidden, attention_weights = decoder(dec_input, features, hidden)

        attention_plot[i] = tf.reshape(attention_weights, (-1, )).numpy()

        predicted_id = tf.random.categorical(predictions, 1)[0][0].numpy()
        result.append(tokenizer.index_word[predicted_id])

        if tokenizer.index_word[predicted_id] == '<end>':
            return result, attention_plot

        dec_input = tf.expand_dims([predicted_id], 0)

    attention_plot = attention_plot[:len(result), :]
    return result, attention_plot
def plot_attention(image, result, attention_plot):
    temp_image = np.array(Image.open(image))

    fig = plt.figure(figsize=(10, 10))

    len_result = len(result)
    for l in range(len_result):
        temp_att = np.resize(attention_plot[l], (8, 8))
        ax = fig.add_subplot(len_result//2, len_result//2, l+1)
        ax.set_title(result[l])
        img = ax.imshow(temp_image)
        ax.imshow(temp_att, cmap='gray', alpha=0.6, extent=img.get_extent())

    plt.tight_layout()
    plt.show()
# captions on the validation set
rid = np.random.randint(0, len(img_name_val))
image = img_name_val[rid]
real_caption = ' '.join([tokenizer.index_word[i] for i in cap_val[rid] if i not in [0]])
result, attention_plot = evaluate(image)

print ('Real Caption:', real_caption)
print ('Prediction Caption:', ' '.join(result))
plot_attention(image, result, attention_plot)

Real Caption: <start> a herd of zebras drinking water at a lake <end>
Prediction Caption: a herd of zebras stand in a road <end>

png

Cobalah gambar Anda sendiri

Untuk bersenang-senang, di bawah ini kami telah menyediakan metode yang dapat Anda gunakan untuk memberi teks pada gambar Anda sendiri dengan model yang baru saja kami latih. Perlu diingat, ini dilatih pada jumlah data yang relatif kecil, dan gambar Anda mungkin berbeda dari data pelatihan (jadi bersiaplah untuk hasil yang aneh!)

image_url = 'https://tensorflow.org/images/surf.jpg'
image_extension = image_url[-4:]
image_path = tf.keras.utils.get_file('image'+image_extension,
                                     origin=image_url)

result, attention_plot = evaluate(image_path)
print ('Prediction Caption:', ' '.join(result))
plot_attention(image_path, result, attention_plot)
# opening the image
Image.open(image_path)
Downloading data from https://tensorflow.org/images/surf.jpg
65536/64400 [==============================] - 0s 3us/step
Prediction Caption: a person is riding a surfboard with surf board <end>

png

png

Langkah selanjutnya

Selamat! Anda baru saja melatih model pembuatan teks dengan perhatian. Selanjutnya, lihat contoh Terjemahan Mesin Neural dengan Perhatian ini . Ini menggunakan arsitektur yang mirip untuk menerjemahkan antara kalimat Spanyol dan Inggris. Anda juga dapat bereksperimen dengan melatih kode di notebook ini pada set data yang berbeda.