練習 - 使用神經網路來分析文字中的情感
若要實際測試,請將您自己的文字輸入模型來看看其執行情況,也就是它在量化該文字中所表達的情感方面有多精確。 在本單元中,您將撰寫 Python 函式來接受文字字串作為輸入、將它傳遞至模型,並傳回情感分數。 然後,您將使用此函式來分析各種文字字串中所表達的情感。
將下列程式碼新增至筆記本結尾的資料格,並執行該資料格:
import string import numpy as np def analyze(text): # Prepare the input by removing punctuation characters, converting # characters to lower case, and removing words containing numbers translator = str.maketrans('', '', string.punctuation) text = text.translate(translator) text = text.lower().split(' ') text = [word for word in text if word.isalpha()] # Generate an input tensor input = [1] for word in text: if word in word_dict and word_dict[word] < top_words: input.append(word_dict[word]) else: input.append(2) padded_input = sequence.pad_sequences([input], maxlen=max_review_length) # Invoke the model and return the result result = model.predict(np.array([padded_input][0]))[0][0] return result
這些陳述式會定義名為
analyze
的函式來接受字串作為輸入,並傳回 0.0 到 1.0 的數字,以量化該字串中所表達的情感。 數字越高,情感越正面。 此函式會清理輸入字串、將它轉換成一份參考load_data
函式所建立字典中文字的整數清單,最後會呼叫模型的predict
函式對文字中的情感評分。使用筆記本來執行下列陳述式:
analyze('Easily the most stellar experience I have ever had.')
輸出是輸入文字中所表達的情感,並以 0.0 到 1.0 的數字表示。 您同意模型的評定嗎?
現在試試看此陳述式:
analyze('The long lines and poor customer service really turned me off.')
模型如何量化這段文字中所表達的情感?
最後使用您自己的輸入字串來測試模型。 結果不會十全十美,但您應該會發現模型在量化情感方面相當精確。 雖然此模型是使用電影評論來定型,但它並不「限於」分析電影評論。 這很合理,因為表達電影好惡的語言,與表達其他不相關主題感受的語言之間,原本就很類似。