Preprocessing con Keras
Il secondo modulo più importante di Keras è keras.preprocessing. Vedrai come usare i moduli e le funzioni principali per preparare i dati grezzi nella forma di input corretta. Keras offre funzionalità che sostituiscono l’approccio basato sul dizionario che hai visto prima.
Userai il modulo keras.preprocessing.text.Tokenizer per creare un dizionario di parole con il metodo .fit_on_texts() e per trasformare i testi in ID numerici che rappresentano l’indice di ogni parola nel dizionario con il metodo .texts_to_sequences().
Poi, usa la funzione .pad_sequences() da keras.preprocessing.sequence per fare in modo che tutte le sequenze abbiano la stessa dimensione (necessaria per il modello) aggiungendo zeri ai testi più corti e tagliando quelli più lunghi.
Questo esercizio fa parte del corso
Reti Neurali Ricorrenti (RNN) per il Language Modeling con Keras
Istruzioni dell'esercizio
- Importa
Tokenizerepad_sequencesdai moduli pertinenti. - Adatta l’oggetto
tokenizerai dati di esempio salvati intexts. - Trasforma i testi in sequenze di indici numerici usando il metodo
.texts_to_sequences(). - Uniforma la lunghezza dei testi applicando il padding.
esercizio interattivo pratico
Prova questo esercizio completando questo codice di esempio.
# Import relevant classes/functions
from tensorflow.keras.preprocessing.text import ____
from tensorflow.keras.preprocessing.sequence import ____
# Build the dictionary of indexes
tokenizer = Tokenizer()
tokenizer.fit_on_texts(____)
# Change texts into sequence of indexes
texts_numeric = tokenizer.____(texts)
print("Number of words in the sample texts: ({0}, {1})".format(len(texts_numeric[0]), len(texts_numeric[1])))
# Pad the sequences
texts_pad = ____(texts_numeric, 60)
print("Now the texts have fixed length: 60. Let's see the first one: \n{0}".format(texts_pad[0]))