這裏的代碼應該是學習《統計學習方法》的實驗練習吧。代碼實現的是《統計學習方法》中第四章樸素貝葉斯法的一個實例,實例如下:
、
實現的步驟也是按照書中的步驟,如有問題,謝謝指正。
import numpy as np
import pickle
import os
def creatDataAndLebels():
Xa = [1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3]
Xb = ['S','M','M','S','S', 'S','M','M','L','L' ,'L','M','M','L','L']
X = [Xa,Xb]
Y = [-1,-1,1,1,-1, -1,-1,1,1,1, 1,1,1,1,-1]
return X,Y
def countFeatureCount(Xi,Y,x,y):
count = 0
for i in range(len(Xi)):
if(Xi[i]==x and Y[i] == y):
count += 1
return count
def trainNB(X,Y):
sizeY = len(Y)
#計算Y中的類別,這裏只有-1,和1,但是我們假裝不知道,然後去統計Y中所有制
YClass = set(Y)
print(YClass)#{1, -1}
#然後我們要計算每一種類別的數目。在這裏也就是-1的個數和1的個數。
PY = {}
PYClass = {}
for y in YClass:
i=0
for yy in Y:
if y == yy:
i += 1
PY.setdefault(str(y),i/sizeY)
PYClass.setdefault(str(y),i) #這個方便後面計算條件概率
print(PY)#{1: 0.6, -1: 0.4}
print(PYClass)#{1: 9, -1: 6}
#到這裏,計算出了P(Y=ci)
#接下來計算條件概率
conditionP = {}
for Xi in X:
XiClass = set(Xi)
for x in XiClass:
for y in YClass:
count = countFeatureCount(Xi,Y,x,y)
conditionP.setdefault(str(x)+str(y),count/PYClass[str(y)])
print(conditionP)
# {'2-1': 0.3333333333333333, 'L1': 0.4444444444444444, 'L-1': 0.16666666666666666, '3-1': 0.16666666666666666, '31':0.4444444444444444,
# 'M-1': 0.3333333333333333, 'S1': 0.1111111111111111, '11': 0.2222222222222222, '1-1': 0.5, 'M1': 0.4444444444444444, 'S-1': 0.5, '21': 0.3333333333333333}
#統計數所有特徵的數目後,計算對應的概率
#計算出條件概率後,學習結束,然後就可以預測了
parameter = [PY,conditionP]
fd = open("test.txt",'wb')
pickle.dump(parameter,fd)
fd.close()
def predictNB(parameter,inputdata):
#print(parameter)
PY = parameter[0]
conditionP = parameter[1]
result = {}
for y in PY:
mul = PY[y]
for x in inputdata:
mul = mul * conditionP[str(x)+str(y)]
result.setdefault(str(y),mul)
best = {'bestLabel':'1','bestValue':0}
for y in result:
if result[y] > best['bestValue']:
best['bestLabel'] = y
best['bestValue'] = result[y]
#print(best)
return best
def testTrain():
X,Y = creatDataAndLebels()
trainNB(X,Y)
return None
def testPredict():
fd = open("test.txt",'rb')
parameter = pickle.load(fd)
fd.close()
a=[2,'M']
#print(parameter[0])
result = predictNB(parameter,a)
return result['bestLabel']
result = testPredict()
print(result)
實驗是這樣的,必須首先執行testTrain方法學習訓練數據,學習完成後,會將訓練的結果寫入文件。測試的時候,先從文件讀取數據,然後根據數據的特徵向量,計算輸出。此處的程序並沒有調用testTrain方法學習訓練數據,因爲之前已經訓練過了。
測試結果如下:
輸入[2,’M’],輸出1
輸入[1,’S’],輸出-1