Rețele Neuronale Recurente (RNN) pentru Modelare a Limbajului cu Keras
David Cecchini
Data Scientist
# Build and compile the model model = Sequential()model.add(Embedding(10000, 128))model.add(LSTM(128, dropout=0.2))model.add(Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
Aceeași arhitectură poate fi utilizată
# Build the model model = Sequential() model.add(Embedding(10000, 128)) model.add(LSTM(128, dropout=0.2))# Output layer has `num_classes` units and uses `softmax` model.add(Dense(num_classes, activation="softmax"))# Compile the model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) ...
Setul de date 20 News Groups
sklearn.datasets import fetch_20newsgroups# Import the function to load the data from sklearn.datasets import fetch_20newsgroups# Download train and test sets news_train = fetch_20newsgroups(subset='train')news_test = fetch_20newsgroups(subset='test')
Datele conțin următoarele atribute:
news_train.DESCR: Documentație.news_train.data: Date text.news_train.filenames: Calea fișierelor pe disc.news_train.target: Indexul numeric al claselor.news_train.target_names: Numele unice ale claselor.# Import modules from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.utils import to_categorical# Create and fit the tokenizer tokenizer = Tokenizer() tokenizer.fit_on_texts(news_train.data)# Create the (X, Y) variables X_train = tokenizer.texts_to_sequences(news_train.data) X_train = pad_sequences(X_train, maxlen=400) Y_train = to_categorical(news_train.target)
Antrenați modelul pe datele de antrenament
# Train the model
model.fit(X_train, Y_train,
batch_size=64, epochs=100)
# Evaluate on test data
model.evaluate(X_test, Y_test)
Rețele Neuronale Recurente (RNN) pentru Modelare a Limbajului cu Keras