IMDB Movie Review Sentiment Analysis Using BERT Fine-Tuning With Tensorflow Keras

Haren Lin
7 min readJun 30, 2021

--

Google BERT

理解了 BERT 在做的事情後,不如找一些資料集來玩玩模型,讓自己更熟悉他的架構吧!還不清楚 BERT 的讀者們,可以參考我先前寫過的文章。

另外,如果你對於 Transformer 的流程也有些疑惑,不仿先參考下面這篇文章,然後再讀 BERT,看完後相信你對於接下來的實作流程,會更有共鳴。

話不多說,直接開始!ㄧ如往常的先引入函式庫以及工具包。

接著我們把資料讀進來,同時我們能觀察一下他的長相:有幾個欄位、標籤有幾種類別、每個類別的分佈等等。此外,處理缺失值。(詳細的程式碼請見最下方 GitHub Link)

資料到手後,別忘了先對文字資料進行處理。我們使用 BERT 的 Tokenizer 來協助我們完成斷詞,並將每個字映射成 ID。

因為我們要使用 BERT-Base 來進行 Fine-Tune,我們勢必將其引進我們自定義的模型當中。那最重要的就是去參考官方文檔確認,在 BERT 的模型他要求的 Input 有什麼,而 Output 又有什麼,我們該如何使用。以下為文檔內容:

This model is called as follows on tokenized text input, an input mask to hold out padding tokens, and segment types when input mixes with different segments.

There are two outputs: a pooled_output of shape [batch_size, 768] with representations for the entire input sequences and a sequence_output of shape [batch_size, max_seq_length, 768] with representations for each input token (in context).

The tokenization of input text can be performed in Python with the FullTokenizer class from tensorflow/models/official/nlp/bert/tokenization.py. Its vocab_file is stored as atf.saved_model.Asset and the do_lower_case flag is stored as a tf.Variable object on the SavedModel. They can be retrieved (using TensorFlow Hub 0.7.0 or newer) as follows:

For complete usage examples, see run_classifier.py and run_squad.py from tensorflow/models/official/nlp/bert/ on GitHub.

我們可以看到他要求的 Input 有三個,分別是:input_word_ids, input_mask, segment_ids,代表 Token 的 ID、有實際 Token 的部分、segment 的 ID。(透過程式碼的呈現,或許會更容易理解!)而 Output 有兩個,分別是:pooled_output, sequence_output,前者是代表整句話,後者是話中每個 Token 的 Embedding Representation。

打鐵趁熱,接下來就來定義這些能幫助我們製造 BERT Layer 輸入資料的函式吧!

接著,定義我們的模型,引入 BERT Base Layer 之後,我們可以針對我們的 Task 去定義不同得 hidden layer 與 output layer,基本上都不需要太過複雜,因為前面 BERT 的 Pre-Trained Model 都有一定的基礎了。而這也是 Transfer Learning 的特色。似乎有點說太多了,看 Code 吧!

接下來,就是把我們 DataFrame 裡面的資料進行 Shuffle 並整理成訓練、驗證、測試資料,並著手模型的訓練嘍!P.S. 如果你是在本機端,千萬部要輕易的將模型丟下去訓練!建議使用 Google Colab GPU/TPU,或是用實驗室的資源!

訓練的模型出爐後,隨即來檢驗一下他的表現如何。

下一集,我們將使用相同的架構,運用在不同的任務上,跑多類別的資料!

This article will be updated at any time! Thanks for your reading. If you like the content, please click the “clap” button. You can also press the follow button to track new articles at any time. Feel free to contact me via LinkedIn or email.

--

--

Haren Lin
Haren Lin

Written by Haren Lin

MSWE @ UC Irvine | MSCS @ NTU GINM | B.S. @ NCCU CS x B.A. @ NCCU ECON | ex-SWE intern @ TrendMicro

No responses yet