¡El Día de la Comunidad de ML es el 9 de noviembre! Únase a nosotros para recibir actualizaciones de TensorFlow, JAX, y más Más información

Clasificación de texto con un RNN

Ver en TensorFlow.org Ejecutar en Google Colab Ver fuente en GitHub Descargar cuaderno

Este tutorial clasificación de texto entrena una red neuronal recurrente en la IMDB gran película de opinión conjunto de datos para el análisis de los sentimientos.

Configuración

import numpy as np

import tensorflow_datasets as tfds
import tensorflow as tf

tfds.disable_progress_bar()

Importación matplotlib y crear una función de ayuda a los gráficos de la trama:

import matplotlib.pyplot as plt


def plot_graphs(history, metric):
  plt.plot(history.history[metric])
  plt.plot(history.history['val_'+metric], '')
  plt.xlabel("Epochs")
  plt.ylabel(metric)
  plt.legend([metric, 'val_'+metric])

Configurar canalización de entrada

El IMDB amplia reseña de la película conjunto de datos es un conjunto de datos binarios de clasificación-todas las opiniones tienen ya sea positiva o sentimiento negativo.

Descargar el conjunto de datos utilizando TFDS . Ver el tutorial de texto de carga para obtener más información sobre cómo cargar este tipo de datos de forma manual.

dataset, info = tfds.load('imdb_reviews', with_info=True,
                          as_supervised=True)
train_dataset, test_dataset = dataset['train'], dataset['test']

train_dataset.element_spec
(TensorSpec(shape=(), dtype=tf.string, name=None),
 TensorSpec(shape=(), dtype=tf.int64, name=None))

Inicialmente, esto devuelve un conjunto de datos de (texto, pares de etiquetas):

for example, label in train_dataset.take(1):
  print('text: ', example.numpy())
  print('label: ', label.numpy())
text:  b"This was an absolutely terrible movie. Don't be lured in by Christopher Walken or Michael Ironside. Both are great actors, but this must simply be their worst role in history. Even their great acting could not redeem this movie's ridiculous storyline. This movie is an early nineties US propaganda piece. The most pathetic scenes were those when the Columbian rebels were making their cases for revolutions. Maria Conchita Alonso appeared phony, and her pseudo-love affair with Walken was nothing but a pathetic emotional plug in a movie that was devoid of any real meaning. I am disappointed that there are movies like this, ruining actor's like Christopher Walken's good name. I could barely sit through it."
label:  0

A continuación mezclar los datos de formación y crear lotes de estos (text, label) pares:

BUFFER_SIZE = 10000
BATCH_SIZE = 64
train_dataset = train_dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
test_dataset = test_dataset.batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
for example, label in train_dataset.take(1):
  print('texts: ', example.numpy()[:3])
  print()
  print('labels: ', label.numpy()[:3])
texts:  [b'Scary Movie 3 (2003) was a bad idea to begin with. The last film was a mediocre effort. Put it next to this load, it\'s a comedy classic. Whilst part two was filled with a lot of dated humor and cheap shots, at least it was funny. There\'s nothing funny about forced humor. Jokes, pratfalls and sight gags are supposed to be naturally funny. Hitting the viewer over the head with tired jokes is not cool. The humor in this film was caters to juvenile imbeciles who\'ll laugh at anything. When they catered to the junior high school crowd, any sense of self respect was tossed out the window. Ring parodies are not funny. I have watched them in comedies since 1998. They\'re so dated. Michael Jackson jokes are not cool either. What\'s even worse is making fun of two broken down has been "performers" whose best days were NEVER.<br /><br />The death of American cinema has been a slow one. Films like this are the nails that are being pounded into it\'s coffin. Whatever happened to real humor? I haven\'t laughed out loud in a movie theater in a long time. Too many bad movies rot the brain. You want proof? Go to your local mega chain video rental store and see what\'s on the shelves. This movie is bad. Don\'t believe the hype. I would rather watch Scary Movie 2 in a continuous loop than to suffer through this poor excuse of a comedy ever again!<br /><br />Definitely not recommended (unless you have a handful of brain cells).'
 b"First of all, I don't understand why some people find this movie so anti-american. Sure, there are moments when the U.S. are accused directly, like at the segments of Youssef Chahine, Ken Loach and, to a certain extent, Mira Nair. But come on, they aren't naive accusations; instead, they are based on real and documented facts, and all the documents that the CIA released about Chile confirms this, for example.<br /><br />But returning to the film itself, what I enjoyed most on it is the variety of moods we find in it. We find children being educated for the respect of the all the people who died in the event; we find a unhappy couple that will be changed by the tragedy of that day; we find common people that have their feelings downgraded on the shadow of the events of September 11 and react differently to this, with dignity or frustration; we even find someone in the movie for who the fall of the towers grounds for a moment of real happiness.<br /><br />All these visions and others - as powerful as these or even more - make a consistent blend and help the spectator to have a glimpse about how different people spread across the world reacted to the events of September 11th. Thus, what we see is a panorama that is much more complex than whites and blacks, and this may make some people infuriated; but this is the world where we live, and in it there is no place for manicheistic ideologies, regardless of what presidents or priests may say us.<br /><br />Finally, I think it's a shame that there isn't even a release date for this movie in the United States of America. It's a shame because most of the american people is asking why this catastrophe happened, and this movie could give some clues to them. This film puts very clearly - differently of what some people of this forum think - that everything we do today will determine our future, and that the errors of the past will affect how we live today."
 b"I'll dispense with the usual comparisons to a certain legendary filmmaker known for his neurotic New Yorker persona, because quite frankly, to draw comparisons with bumbling loser Josh Kornbluth, is just an insult to any such director. I will also avoid mentioning the spot-on satire `Office Space' in the same breath as this celluloid catastrophe. I can, however, compare it to waking up during your own surgery \xc2\x96 it's painful to watch and you wonder whether the surgeons really know what they're doing. Haiku Tunnel is the kind of film you wish they'd pulled the plug on in its early stages of production. It was cruel to let it live and as a result, audiences around the world are being made to suffer.<br /><br />The film's premise \xc2\x96 if indeed it has one \xc2\x96 is not even worth discussing, but for the sake of caution I will. Josh Kornbluth, a temp worker with severe commitment-phobia, is offered a permanent job. His main duty is to mail out 17 high priority letters for his boss. But ludicrously, he is unable to perform this simple task. My reaction? Big deal! That's not a story\xc2\x85 it's a passing thought at best - one that should've passed any self-respecting filmmaker by. <br /><br />The leading actor \xc2\x96 if you can call him that \xc2\x96 is a clumsy buffoon of a man, with chubby features, a receding, untamed hairline, and a series of facial expressions that range from cringe-making to plain disturbing. Where o where did the director find this schmuck? What's that you say\xc2\x85\xc2\x85 he is the director? Oh, my mistake. Playing yourself in your own embarrassment of a screenplay is one thing, but I suspect that Mr Kornbluth isn't that convincing as a human being, let alone an actor. Rest assured, this is by no means an aimless character assassination, but never before have I been so riled up by an actor's on-screen presence! My frustration was further confounded by his incessant to-camera monologues in between scenes. I mean, as if the viewer needs an ounce of intelligence to comprehend this drivel, Kornbluth insults us further by `explaining' the action (first rule of filmmaking: `dramatize exposition'\xc2\x85 show, don't tell). Who does this guy think he is? He has no charisma, no charm, and judging by his Hawaiian shirts, no sense of style. His casting agent should be shot point blank!<br /><br />The supporting actors do nothing to relieve the intense boredom I felt, with but one exception. Patricia Scanlon puts in a very funny appearance as Helen the ex-secretary, who has been driven insane by her old boss, and makes harassing phone calls from her basement, while holding a flashlight under her face. This did make me chuckle to myself, but the moment soon passed and I was back to checking my watch for the remainder of the film.<br /><br />The film's title is also a misnomer. Haiku Tunnel has nothing to do with the ancient form of Japanese poetry. Don't be fooled into thinking this is an art house film because of its pretentious-sounding title or the fact that it only played in a handful of cinemas and made no money at the box office\xc2\x85\xc2\x85\xc2\x85 there's a very good reason for that!<br /><br />"]

labels:  [0 1 0]

Crea el codificador de texto

El texto en bruto cargado por tfds necesita ser procesada antes de que pueda ser utilizado en un modelo. La forma más sencilla de texto proceso de formación está utilizando el TextVectorization capa. Esta capa tiene muchas capacidades, pero este tutorial se adhiere al comportamiento predeterminado.

Crear la capa, y aprobar el texto del conjunto de datos a la capa de .adapt método:

VOCAB_SIZE = 1000
encoder = tf.keras.layers.TextVectorization(
    max_tokens=VOCAB_SIZE)
encoder.adapt(train_dataset.map(lambda text, label: text))

El .adapt método establece el vocabulario de la capa. Aquí están las primeras 20 fichas. Después del relleno y los tokens desconocidos, se ordenan por frecuencia:

vocab = np.array(encoder.get_vocabulary())
vocab[:20]
array(['', '[UNK]', 'the', 'and', 'a', 'of', 'to', 'is', 'in', 'it', 'i',
       'this', 'that', 'br', 'was', 'as', 'for', 'with', 'movie', 'but'],
      dtype='<U14')

Una vez que se establece el vocabulario, la capa puede codificar texto en índices. Los tensores de índices se 0-acolchado en la secuencia más larga en el lote (a menos que establezca un fijo output_sequence_length ):

encoded_example = encoder(example)[:3].numpy()
encoded_example
array([[633,  18, 442, ...,   0,   0,   0],
       [ 86,   5,  32, ...,   0,   0,   0],
       [527,   1,  17, ...,   0,   0,   0]])

Con la configuración predeterminada, el proceso no es completamente reversible. Hay tres razones principales para ello:

  1. El valor por defecto para preprocessing.TextVectorization 's standardize argumento es "lower_and_strip_punctuation" .
  2. El tamaño limitado del vocabulario y la falta de respaldo basado en caracteres dan como resultado algunos tokens desconocidos.
for n in range(3):
  print("Original: ", example[n].numpy())
  print("Round-trip: ", " ".join(vocab[encoded_example[n]]))
  print()
Original:  b'Scary Movie 3 (2003) was a bad idea to begin with. The last film was a mediocre effort. Put it next to this load, it\'s a comedy classic. Whilst part two was filled with a lot of dated humor and cheap shots, at least it was funny. There\'s nothing funny about forced humor. Jokes, pratfalls and sight gags are supposed to be naturally funny. Hitting the viewer over the head with tired jokes is not cool. The humor in this film was caters to juvenile imbeciles who\'ll laugh at anything. When they catered to the junior high school crowd, any sense of self respect was tossed out the window. Ring parodies are not funny. I have watched them in comedies since 1998. They\'re so dated. Michael Jackson jokes are not cool either. What\'s even worse is making fun of two broken down has been "performers" whose best days were NEVER.<br /><br />The death of American cinema has been a slow one. Films like this are the nails that are being pounded into it\'s coffin. Whatever happened to real humor? I haven\'t laughed out loud in a movie theater in a long time. Too many bad movies rot the brain. You want proof? Go to your local mega chain video rental store and see what\'s on the shelves. This movie is bad. Don\'t believe the hype. I would rather watch Scary Movie 2 in a continuous loop than to suffer through this poor excuse of a comedy ever again!<br /><br />Definitely not recommended (unless you have a handful of brain cells).'
Round-trip:  scary movie 3 [UNK] was a bad idea to begin with the last film was a [UNK] effort put it next to this [UNK] its a comedy classic [UNK] part two was [UNK] with a lot of [UNK] humor and cheap shots at least it was funny theres nothing funny about forced humor jokes [UNK] and [UNK] [UNK] are supposed to be [UNK] funny [UNK] the viewer over the head with [UNK] jokes is not cool the humor in this film was [UNK] to [UNK] [UNK] [UNK] laugh at anything when they [UNK] to the [UNK] high school [UNK] any sense of [UNK] [UNK] was [UNK] out the [UNK] [UNK] [UNK] are not funny i have watched them in [UNK] since [UNK] theyre so [UNK] michael [UNK] jokes are not cool either whats even worse is making fun of two [UNK] down has been [UNK] whose best days were [UNK] br the death of american cinema has been a slow one films like this are the [UNK] that are being [UNK] into its [UNK] whatever happened to real humor i havent [UNK] out [UNK] in a movie theater in a long time too many bad movies [UNK] the [UNK] you want [UNK] go to your local [UNK] [UNK] video [UNK] [UNK] and see whats on the [UNK] this movie is bad dont believe the [UNK] i would rather watch scary movie 2 in a [UNK] [UNK] than to [UNK] through this poor [UNK] of a comedy ever [UNK] br definitely not [UNK] unless you have a [UNK] of [UNK] [UNK]                                                                                                                                                                                                                                                                                                                                                                                                                                                                              

Original:  b"First of all, I don't understand why some people find this movie so anti-american. Sure, there are moments when the U.S. are accused directly, like at the segments of Youssef Chahine, Ken Loach and, to a certain extent, Mira Nair. But come on, they aren't naive accusations; instead, they are based on real and documented facts, and all the documents that the CIA released about Chile confirms this, for example.<br /><br />But returning to the film itself, what I enjoyed most on it is the variety of moods we find in it. We find children being educated for the respect of the all the people who died in the event; we find a unhappy couple that will be changed by the tragedy of that day; we find common people that have their feelings downgraded on the shadow of the events of September 11 and react differently to this, with dignity or frustration; we even find someone in the movie for who the fall of the towers grounds for a moment of real happiness.<br /><br />All these visions and others - as powerful as these or even more - make a consistent blend and help the spectator to have a glimpse about how different people spread across the world reacted to the events of September 11th. Thus, what we see is a panorama that is much more complex than whites and blacks, and this may make some people infuriated; but this is the world where we live, and in it there is no place for manicheistic ideologies, regardless of what presidents or priests may say us.<br /><br />Finally, I think it's a shame that there isn't even a release date for this movie in the United States of America. It's a shame because most of the american people is asking why this catastrophe happened, and this movie could give some clues to them. This film puts very clearly - differently of what some people of this forum think - that everything we do today will determine our future, and that the errors of the past will affect how we live today."
Round-trip:  first of all i dont understand why some people find this movie so [UNK] sure there are moments when the us are [UNK] [UNK] like at the [UNK] of [UNK] [UNK] [UNK] [UNK] and to a certain [UNK] [UNK] [UNK] but come on they arent [UNK] [UNK] instead they are based on real and [UNK] [UNK] and all the [UNK] that the [UNK] released about [UNK] [UNK] this for [UNK] br but [UNK] to the film itself what i enjoyed most on it is the [UNK] of [UNK] we find in it we find children being [UNK] for the [UNK] of the all the people who [UNK] in the [UNK] we find a [UNK] couple that will be [UNK] by the [UNK] of that day we find [UNK] people that have their [UNK] [UNK] on the [UNK] of the events of [UNK] [UNK] and [UNK] [UNK] to this with [UNK] or [UNK] we even find someone in the movie for who the fall of the [UNK] [UNK] for a moment of real [UNK] br all these [UNK] and others as powerful as these or even more make a [UNK] [UNK] and help the [UNK] to have a [UNK] about how different people [UNK] across the world [UNK] to the events of [UNK] [UNK] [UNK] what we see is a [UNK] that is much more [UNK] than [UNK] and [UNK] and this may make some people [UNK] but this is the world where we live and in it there is no place for [UNK] [UNK] [UNK] of what [UNK] or [UNK] may say [UNK] br finally i think its a shame that there isnt even a release [UNK] for this movie in the [UNK] [UNK] of america its a shame because most of the american people is [UNK] why this [UNK] happened and this movie could give some [UNK] to them this film [UNK] very clearly [UNK] of what some people of this [UNK] think that everything we do today will [UNK] our future and that the [UNK] of the past will [UNK] how we live today                                                                                                                                                                                                                                                                                                                                                                                        

Original:  b"I'll dispense with the usual comparisons to a certain legendary filmmaker known for his neurotic New Yorker persona, because quite frankly, to draw comparisons with bumbling loser Josh Kornbluth, is just an insult to any such director. I will also avoid mentioning the spot-on satire `Office Space' in the same breath as this celluloid catastrophe. I can, however, compare it to waking up during your own surgery \xc2\x96 it's painful to watch and you wonder whether the surgeons really know what they're doing. Haiku Tunnel is the kind of film you wish they'd pulled the plug on in its early stages of production. It was cruel to let it live and as a result, audiences around the world are being made to suffer.<br /><br />The film's premise \xc2\x96 if indeed it has one \xc2\x96 is not even worth discussing, but for the sake of caution I will. Josh Kornbluth, a temp worker with severe commitment-phobia, is offered a permanent job. His main duty is to mail out 17 high priority letters for his boss. But ludicrously, he is unable to perform this simple task. My reaction? Big deal! That's not a story\xc2\x85 it's a passing thought at best - one that should've passed any self-respecting filmmaker by. <br /><br />The leading actor \xc2\x96 if you can call him that \xc2\x96 is a clumsy buffoon of a man, with chubby features, a receding, untamed hairline, and a series of facial expressions that range from cringe-making to plain disturbing. Where o where did the director find this schmuck? What's that you say\xc2\x85\xc2\x85 he is the director? Oh, my mistake. Playing yourself in your own embarrassment of a screenplay is one thing, but I suspect that Mr Kornbluth isn't that convincing as a human being, let alone an actor. Rest assured, this is by no means an aimless character assassination, but never before have I been so riled up by an actor's on-screen presence! My frustration was further confounded by his incessant to-camera monologues in between scenes. I mean, as if the viewer needs an ounce of intelligence to comprehend this drivel, Kornbluth insults us further by `explaining' the action (first rule of filmmaking: `dramatize exposition'\xc2\x85 show, don't tell). Who does this guy think he is? He has no charisma, no charm, and judging by his Hawaiian shirts, no sense of style. His casting agent should be shot point blank!<br /><br />The supporting actors do nothing to relieve the intense boredom I felt, with but one exception. Patricia Scanlon puts in a very funny appearance as Helen the ex-secretary, who has been driven insane by her old boss, and makes harassing phone calls from her basement, while holding a flashlight under her face. This did make me chuckle to myself, but the moment soon passed and I was back to checking my watch for the remainder of the film.<br /><br />The film's title is also a misnomer. Haiku Tunnel has nothing to do with the ancient form of Japanese poetry. Don't be fooled into thinking this is an art house film because of its pretentious-sounding title or the fact that it only played in a handful of cinemas and made no money at the box office\xc2\x85\xc2\x85\xc2\x85 there's a very good reason for that!<br /><br />"
Round-trip:  ill [UNK] with the usual [UNK] to a certain [UNK] [UNK] known for his [UNK] new [UNK] [UNK] because quite [UNK] to [UNK] [UNK] with [UNK] [UNK] [UNK] [UNK] is just an [UNK] to any such director i will also avoid [UNK] the [UNK] [UNK] [UNK] space in the same [UNK] as this [UNK] [UNK] i can however [UNK] it to [UNK] up during your own [UNK] – its [UNK] to watch and you wonder whether the [UNK] really know what theyre doing [UNK] [UNK] is the kind of film you wish [UNK] [UNK] the [UNK] on in its early [UNK] of production it was [UNK] to let it live and as a result [UNK] around the world are being made to [UNK] br the films premise – if indeed it has one – is not even worth [UNK] but for the [UNK] of [UNK] i will [UNK] [UNK] a [UNK] [UNK] with [UNK] [UNK] is [UNK] a [UNK] job his main [UNK] is to [UNK] out [UNK] high [UNK] [UNK] for his [UNK] but [UNK] he is [UNK] to [UNK] this simple [UNK] my [UNK] big deal thats not a [UNK] its a [UNK] thought at best one that [UNK] [UNK] any [UNK] [UNK] by br br the leading actor – if you can call him that – is a [UNK] [UNK] of a man with [UNK] features a [UNK] [UNK] [UNK] and a series of [UNK] [UNK] that [UNK] from [UNK] to [UNK] [UNK] where [UNK] where did the director find this [UNK] whats that you [UNK] he is the director oh my [UNK] playing yourself in your own [UNK] of a screenplay is one thing but i [UNK] that mr [UNK] isnt that [UNK] as a human being let alone an actor rest [UNK] this is by no means an [UNK] character [UNK] but never before have i been so [UNK] up by an actors [UNK] [UNK] my [UNK] was [UNK] [UNK] by his [UNK] [UNK] [UNK] in between scenes i mean as if the viewer needs an [UNK] of [UNK] to [UNK] this [UNK] [UNK] [UNK] us [UNK] by [UNK] the action first [UNK] of [UNK] [UNK] [UNK] show dont tell who does this guy think he is he has no [UNK] no [UNK] and [UNK] by his [UNK] [UNK] no sense of style his casting [UNK] should be shot point [UNK] br the supporting actors do nothing to [UNK] the [UNK] [UNK] i felt with but one [UNK] [UNK] [UNK] [UNK] in a very funny [UNK] as [UNK] the [UNK] who has been [UNK] [UNK] by her old [UNK] and makes [UNK] [UNK] [UNK] from her [UNK] while [UNK] a [UNK] under her face this did make me [UNK] to myself but the moment soon [UNK] and i was back to [UNK] my watch for the [UNK] of the filmbr br the films title is also a [UNK] [UNK] [UNK] has nothing to do with the [UNK] form of japanese [UNK] dont be [UNK] into thinking this is an art house film because of its [UNK] title or the fact that it only played in a [UNK] of [UNK] and made no money at the [UNK] [UNK] theres a very good reason for [UNK] br

Crea el modelo

Un dibujo del flujo de información en el modelo.

Arriba hay un diagrama del modelo.

  1. Este modelo se puede construir como un tf.keras.Sequential .

  2. La primera capa es la encoder , que convierte el texto en una secuencia de índices de tokens.

  3. Después del codificador hay una capa de incrustación. Una capa de incrustación almacena un vector por palabra. Cuando se llama, convierte las secuencias de índices de palabras en secuencias de vectores. Estos vectores se pueden entrenar. Después del entrenamiento (con suficientes datos), las palabras con significados similares a menudo tienen vectores similares.

    Este índice de búsqueda es mucho más eficiente que la operación equivalente de pasar un vector codificada de una sola caliente a través de un tf.keras.layers.Dense capa.

  4. Una red neuronal recurrente (RNN) procesa la entrada de secuencia iterando a través de los elementos. Los RNN pasan las salidas de un paso de tiempo a su entrada en el siguiente paso de tiempo.

    El tf.keras.layers.Bidirectional envoltura también se puede utilizar con una capa RNN. Esto propaga la entrada hacia adelante y hacia atrás a través de la capa RNN y luego concatena la salida final.

    • La principal ventaja de un RNN bidireccional es que la señal desde el principio de la entrada no necesita procesarse hasta el final en cada paso de tiempo para afectar la salida.

    • La principal desventaja de un RNN bidireccional es que no puede transmitir predicciones de manera eficiente a medida que se agregan palabras al final.

  5. Después de la RNN ha convertido la secuencia para un único vector de los dos layers.Dense hacer algo de procesamiento final, y convertir de esta representación vectorial a un solo logit como la salida de clasificación.

El código para implementar esto es el siguiente:

model = tf.keras.Sequential([
    encoder,
    tf.keras.layers.Embedding(
        input_dim=len(encoder.get_vocabulary()),
        output_dim=64,
        # Use masking to handle the variable sequence lengths
        mask_zero=True),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(1)
])

Tenga en cuenta que aquí se utiliza el modelo secuencial de Keras, ya que todas las capas del modelo solo tienen una entrada única y producen una salida única. En caso de que desee utilizar la capa RNN con estado, es posible que desee crear su modelo con la API funcional de Keras o la subclase de modelos para poder recuperar y reutilizar los estados de la capa RNN. Por favor, compruebe guía Keras RNN para más detalles.

Los capa de encaje usos de enmascaramiento para manejar la secuencia variable longitudes. Todas las capas después de la Embedding enmascaramiento de apoyo:

print([layer.supports_masking for layer in model.layers])
[False, True, True, True, True]

Para confirmar que esto funciona como se esperaba, evalúe una oración dos veces. Primero, solo para que no haya relleno para enmascarar:

# predict on a sample text without padding.

sample_text = ('The movie was cool. The animation and the graphics '
               'were out of this world. I would recommend this movie.')
predictions = model.predict(np.array([sample_text]))
print(predictions[0])
[0.01226519]

Ahora, evalúelo nuevamente en un lote con una oración más larga. El resultado debería ser idéntico:

# predict on a sample text with padding

padding = "the " * 2000
predictions = model.predict(np.array([sample_text, padding]))
print(predictions[0])
[0.01226519]

Compile el modelo de Keras para configurar el proceso de entrenamiento:

model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              optimizer=tf.keras.optimizers.Adam(1e-4),
              metrics=['accuracy'])

Entrena el modelo

history = model.fit(train_dataset, epochs=10,
                    validation_data=test_dataset,
                    validation_steps=30)
Epoch 1/10
391/391 [==============================] - 44s 89ms/step - loss: 0.6525 - accuracy: 0.5551 - val_loss: 0.5196 - val_accuracy: 0.7312
Epoch 2/10
391/391 [==============================] - 31s 78ms/step - loss: 0.4593 - accuracy: 0.7856 - val_loss: 0.4159 - val_accuracy: 0.8276
Epoch 3/10
391/391 [==============================] - 32s 79ms/step - loss: 0.3769 - accuracy: 0.8395 - val_loss: 0.3691 - val_accuracy: 0.8385
Epoch 4/10
391/391 [==============================] - 33s 82ms/step - loss: 0.3399 - accuracy: 0.8547 - val_loss: 0.3643 - val_accuracy: 0.8370
Epoch 5/10
391/391 [==============================] - 33s 83ms/step - loss: 0.3214 - accuracy: 0.8629 - val_loss: 0.3367 - val_accuracy: 0.8531
Epoch 6/10
391/391 [==============================] - 32s 81ms/step - loss: 0.3118 - accuracy: 0.8675 - val_loss: 0.3414 - val_accuracy: 0.8620
Epoch 7/10
391/391 [==============================] - 32s 80ms/step - loss: 0.3075 - accuracy: 0.8697 - val_loss: 0.3385 - val_accuracy: 0.8578
Epoch 8/10
391/391 [==============================] - 33s 83ms/step - loss: 0.3022 - accuracy: 0.8731 - val_loss: 0.3317 - val_accuracy: 0.8484
Epoch 9/10
391/391 [==============================] - 32s 81ms/step - loss: 0.3000 - accuracy: 0.8742 - val_loss: 0.3241 - val_accuracy: 0.8557
Epoch 10/10
391/391 [==============================] - 31s 77ms/step - loss: 0.2972 - accuracy: 0.8732 - val_loss: 0.3216 - val_accuracy: 0.8552
test_loss, test_acc = model.evaluate(test_dataset)

print('Test Loss:', test_loss)
print('Test Accuracy:', test_acc)
391/391 [==============================] - 15s 38ms/step - loss: 0.3170 - accuracy: 0.8618
Test Loss: 0.3169540762901306
Test Accuracy: 0.861840009689331
plt.figure(figsize=(16, 8))
plt.subplot(1, 2, 1)
plot_graphs(history, 'accuracy')
plt.ylim(None, 1)
plt.subplot(1, 2, 2)
plot_graphs(history, 'loss')
plt.ylim(0, None)
(0.0, 0.6703125551342964)

png

Ejecute una predicción en una nueva oración:

Si la predicción es> = 0.0, es positiva, de lo contrario es negativa.

sample_text = ('The movie was cool. The animation and the graphics '
               'were out of this world. I would recommend this movie.')
predictions = model.predict(np.array([sample_text]))

Apila dos o más capas de LSTM

Capas recurrentes Keras tienen dos modos disponibles que son controlados por el return_sequences argumento del constructor:

  • Si False devuelve sólo el último de salida para cada secuencia de entrada (un tensor 2D de forma (batch_size, output_features)). Este es el predeterminado, utilizado en el modelo anterior.

  • Si True se devuelven las secuencias completas de salidas sucesivas para cada paso de tiempo (un tensor 3D de la forma (batch_size, timesteps, output_features) ).

Esto es lo que el flujo de información como se ve con return_sequences=True :

layered_bidirectional

Lo interesante acerca del uso de un RNN con return_sequences=True es que la salida todavía tiene 3 ejes, como la entrada, por lo que se puede pasar a otra capa RNN, como este:

model = tf.keras.Sequential([
    encoder,
    tf.keras.layers.Embedding(len(encoder.get_vocabulary()), 64, mask_zero=True),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64,  return_sequences=True)),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(1)
])
model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              optimizer=tf.keras.optimizers.Adam(1e-4),
              metrics=['accuracy'])
history = model.fit(train_dataset, epochs=10,
                    validation_data=test_dataset,
                    validation_steps=30)
Epoch 1/10
391/391 [==============================] - 73s 152ms/step - loss: 0.6501 - accuracy: 0.5531 - val_loss: 0.4503 - val_accuracy: 0.7943
Epoch 2/10
391/391 [==============================] - 54s 137ms/step - loss: 0.3922 - accuracy: 0.8259 - val_loss: 0.3550 - val_accuracy: 0.8448
Epoch 3/10
391/391 [==============================] - 53s 135ms/step - loss: 0.3395 - accuracy: 0.8548 - val_loss: 0.3345 - val_accuracy: 0.8500
Epoch 4/10
391/391 [==============================] - 53s 135ms/step - loss: 0.3222 - accuracy: 0.8645 - val_loss: 0.3248 - val_accuracy: 0.8578
Epoch 5/10
391/391 [==============================] - 54s 137ms/step - loss: 0.3158 - accuracy: 0.8662 - val_loss: 0.3232 - val_accuracy: 0.8604
Epoch 6/10
391/391 [==============================] - 52s 131ms/step - loss: 0.3056 - accuracy: 0.8698 - val_loss: 0.3233 - val_accuracy: 0.8573
Epoch 7/10
391/391 [==============================] - 52s 130ms/step - loss: 0.3032 - accuracy: 0.8712 - val_loss: 0.3197 - val_accuracy: 0.8526
Epoch 8/10
391/391 [==============================] - 51s 130ms/step - loss: 0.3041 - accuracy: 0.8688 - val_loss: 0.3210 - val_accuracy: 0.8552
Epoch 9/10
391/391 [==============================] - 54s 136ms/step - loss: 0.3007 - accuracy: 0.8726 - val_loss: 0.3178 - val_accuracy: 0.8589
Epoch 10/10
391/391 [==============================] - 55s 138ms/step - loss: 0.2931 - accuracy: 0.8745 - val_loss: 0.3416 - val_accuracy: 0.8656
test_loss, test_acc = model.evaluate(test_dataset)

print('Test Loss:', test_loss)
print('Test Accuracy:', test_acc)
391/391 [==============================] - 26s 66ms/step - loss: 0.3409 - accuracy: 0.8628
Test Loss: 0.3409377634525299
Test Accuracy: 0.8628000020980835
# predict on a sample text without padding.

sample_text = ('The movie was not good. The animation and the graphics '
               'were terrible. I would not recommend this movie.')
predictions = model.predict(np.array([sample_text]))
print(predictions)
[[-1.9127669]]
plt.figure(figsize=(16, 6))
plt.subplot(1, 2, 1)
plot_graphs(history, 'accuracy')
plt.subplot(1, 2, 2)
plot_graphs(history, 'loss')

png

Echa un vistazo a otras capas recurrentes existentes, tales como capas GRU .

Si usted está en la construcción de interestied RNNs personalizados, consulte la Guía de Keras RNN .