1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
def buildStump(dataIn,classLabel,D): #D为输入的分类权重,后面会用到 #输入数据,正确分类,迭代系数 n=dataIn.shape[1] m=dataIn.shape[0] numStep=10.0 bestStump={} bestClass=np.zeros((m,1)) minError=np.inf for i in range(0,n): iAxis=dataIn[:,i] minAxis=min(iAxis) maxAxis=max(iAxis) stepSize=(maxAxis-minAxis)/numStep #考虑大于和小于两种分类情况 for ineq in ['lt','gt']: for j in range(-1,int(numStep)+1): #每次计算错误值 threshVal=minAxis+stepSize*float(j) #从threshVal值处对i特征值对应数据进行分类 predictCategory=stumpClassify(dataIn,i,threshVal,ineq) #初始化误差值矩阵 errArr=np.ones((m,1)) #预测正确的点误差矩阵值为0,其他点为1 errArr[predictCategory==classLabel]=0 #误差矩阵乘以权重得到该threshVal的分类总误差, errSum=np.dot(D.T,errArr) #更新误差最小的threshVal if errSum<minError: minError=errSum bestClass=predictCategory.copy() bestStump['dim']=i bestStump['threshVal']=threshVal bestStump['ineq']=ineq print('j',j,'ineq',ineq,'split',i,'nthresh',threshVal,'nerrorsum',errSum) return bestStump,minError,bestClass classLabel=np.array(([[1],[-1],[-1],[1],[1],[1]])) buildStump(dataIn,classLabel,D) Out[56]: #得到当前权重下最佳分类 #分类的特征为0列对应的特征,分类值为4,错误率0.167,分类结果[-1,-1,-1,1,1,1] ({'dim': 0, 'ineq': 'lt', 'threshVal': 4.0}, array([[ 0.16666667]]), array([[-1.], [-1.], [-1.], [ 1.], [ 1.], [ 1.]]))
|
近期评论