多分类模型

使用 Keras 构建语言建模的循环神经网络(RNN)

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'])
使用 Keras 构建语言建模的循环神经网络(RNN)

模型架构

可复用相同的架构

# 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']) ...
使用 Keras 构建语言建模的循环神经网络(RNN)

20 News Group 数据集

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')
使用 Keras 构建语言建模的循环神经网络(RNN)

20 News Group 数据集

数据包含以下属性:

  • news_train.DESCR:文档说明。
  • news_train.data:文本数据。
  • news_train.filenames:磁盘文件路径。
  • news_train.target:类别的数值索引。
  • news_train.target_names:类别名称。
使用 Keras 构建语言建模的循环神经网络(RNN)

文本预处理

# 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)
使用 Keras 构建语言建模的循环神经网络(RNN)

数据训练

在训练集上训练模型

# Train the model
model.fit(X_train, Y_train, 
          batch_size=64, epochs=100)

# Evaluate on test data
model.evaluate(X_test, Y_test)
使用 Keras 构建语言建模的循环神经网络(RNN)

Passons à la pratique !

使用 Keras 构建语言建模的循环神经网络(RNN)

Preparing Video For Download...