多類別分類模型

使用 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)

一起來練習吧!

使用 Keras 建立語言模型的循環神經網路(RNN)

Preparing Video For Download...