1.特征向量 每一個有效詞匯在郵件中出現的次數(使用一維列表方法) word 詞匯出現的次數 一維列表.count(word) 2.將列表轉換為數組形式 array(參數) 創建垃圾郵件,正常郵件訓練集 array(列表對象 或 表達式) 3.使用 朴素貝葉斯算法 model = MultinomialNB() 4.進行訓練模型 model.fit model.fit(array數組,array數組) 5.對指定 topWords 數據使用函數 map(lambda x:words.count(x),topWords) 6.預測數據 model.predict ,返回值為 0 或 1 result = model.predict(array數組.reshape(1,-1))[0] 7.查看在不同區間的概率 model.predict_proba(array數組.reshape(1,-1)) 8.條件語句,預測的結果便於區分 1 為垃圾郵件,0 為 正常郵件 return "垃圾郵件" if result == 1 else "正常郵件" 程序: # 全部訓練集中出現次數最多的前 600 個單詞 topWords = getTopWords(600) vectors = [ ] for words in allWords: temp = list(map(lambda x:words.count(x),topWords)) # 獲取前600個單詞的出現的個數 vectors.append(temp) vectors = array(vectors) # 對訓練集中的數據給定一個標簽 # 0.txt~99.txt 為垃圾郵件,0 # 100~140 為有效郵件,1 labels = array([1] * 100 + [0] * 41) # 創建模型 model = MultinomialNB() model.fit(vectors,labels) # 訓練樣本數和標簽 def predict(txtFile): words = getWordsFromFile(txtFile) # 獲取有效字符 currentVector = array(tuple( lambda x:words.count(x),topWords )) # 查看有效詞匯個數 result = model.predict(currentVector.reshape(1,-1))[0] # 查看預測的概率 print(model.predict_proba(currentVector.reshape(1,-1))) return "垃圾郵件" if result == 1 else "正常郵件"
2020-04-11