開始使用免費開始

情感分析

在影片練習中,你看過序列到序列模型的多種應用。在這個練習中,你會看到如何使用預先訓練好的模型來做情感分析。

環境中已經載入了變數 model,代表模型。此外,斷詞後的測試集變數 X_testy_test,以及來自 IMDb、已預先處理過的原始文字資料 sentences 也都可用。之後在課程中,你會學到如何預先處理文字資料,以及如何使用 Keras 建立並訓練模型。

你將使用這個預訓練模型來取得情感的預測。模型會回傳介於 0 到 1 的數值,代表句子為正向情感的機率。因此,你需要建立一個決策規則,把預測結果標記為正向或負向。

本練習屬於課程

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

檢視課程

練習說明

  • 使用 .predict() 方法對測試資料進行預測。
  • 若預測值大於 0.5,將其設為 "positive",否則設為 "negative",並把結果存到變數 pred_sentiment
  • 建立一個 pd.DataFrame,包含預先處理的文字、上一個步驟得到的預測,以及在變數 y_test 中的真實標籤。
  • 使用 .head() 方法印出前幾列。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Inspect the first sentence on `X_test`
print(X_test[0])

# Get the predicion for all the sentences
pred = model.predict(____)

# Transform the predition into positive (> 0.5) or negative (<= 0.5)
pred_sentiment = ["positive" if x>____ else "negative" for x in pred]

# Create a data frame with sentences, predictions and true values
result = pd.DataFrame({'sentence': sentences, 'y_pred': ____, 'y_true': y_test})

# Print the first lines of the data frame
print(result.____)
編輯並執行程式碼