決策樹IMDB數據集電影評測分類


@

決策樹IMDB數據集電影評測分類(二分類問題)

1. 數據集講解:

該數據集是IMDB電影數據集的一個子集,已經划分好了測試集和訓練集,訓練集包括25000條電影評論,測試集也有25000條,該數據集已經經過預處理,將每條評論的具體單詞序列轉化為詞庫里的整數序列,其中每個整數代表該單詞在詞庫里的位置。例如,整數104代表該單詞是詞庫的第104個單詞。為實驗簡單,詞庫僅僅保留了10000個最常出現的單詞,低頻詞匯被舍棄。每條評論都具有一個標簽,0表示為負面評論,1表示為正面評論。

訓練數據在train_data.txt文件下,每一行為一條評論,訓練集標簽在train_labels.txt文件下,每一行為一條評論的標簽;測試數據在test_data.txt文件下,測試數據標簽未給出。

2. 代碼實現:

a) 取出數據集:

從txt中取出訓練集與測試集:

with open("test/test_data.txt", "rb") as fr:

  test_data_n = [inst.decode().strip().split(' ') for inst in fr.readlines()]

  test_data = [[int(element) for element in line] for line in test_data_n]

test_data = np.array(test_data)

b) 數據處理:

對每條評論,先將其解碼為英文單詞,再鍵值顛倒,將整數索引映射為單詞。

把整數序列編碼為二進制序列。

最后把訓練集標簽向量化。

# 將某條評論解碼為英文單詞

word_index = imdb.get_word_index() # word_index是一個將單詞映射為整數索引的字典

reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])

 

\# 鍵值顛倒,將整數索引映射為單詞

decode_review = ' '.join(

  [reverse_word_index.get(i - 3, '?') for i in train_data[0]]

) 

\# 將評論解碼

\# 注意,索引減去了3,因為0,1,2是為padding填充

\# "start sequence"序列開始,"unknow"未知詞分別保留的索引

 

\# 將整數序列編碼為二進制矩陣

def vectorize_sequences(sequences, dimension=10000):

  results = np.zeros((len(sequences), dimension)) # 創建一個形狀為(len(sequences), dimension)的矩陣

  for i, sequence in enumerate(sequences):

​    results[i, sequence] = 1 # 將results[i]的指定索引設為 1

  return results

 

x_train = vectorize_sequences(train_data)

x_test = vectorize_sequences(test_data)

\# 標簽向量化

y_train = np.asarray(train_labels).astype('float32')

 

c) 建立決策樹:

decision_tree_classifier = DecisionTreeClassifier()

decision_tree_classifier.fit(x_train, y_train)

d) 輸出測試集上的預測結果:

將結果寫入txt

decision_tree_output = decision_tree_classifier.predict(x_test)

des = decision_tree_output.astype(int)

np.savetxt('Text3_result.txt', des, fmt='%d', delimiter='\n')

print(decision_tree_output)

3. 參數調整:

使用設置max_depth控制樹的深度,置random_state = 30 不變,使用for循環尋找,發現深度為25時,accuracy_score最大。
在這里插入圖片描述

4. 實驗結果:

分離出一部分作為測試集,在測試集上的accuracy_score不太理想:

在這里插入圖片描述

考慮應該是決策樹模型並不適合處理該問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM