9.5 模型树

2023-07-21 08:08:2011:38 400
声音简介

#==========模型树的叶节点生成函数=========  

def linearSolve(dataSet):           #执行简单的线性回归  

    m,n       = shape(dataSet)  

    X         = mat(ones((m,n)))  

    Y         = mat(ones((m,1)))  

    X[:, 1:n] = dataSet[:, 0:n-1]  

    Y         = dataSet[:, -1]      #将X,Y中的数据格式化  

    xTx       = X.T*X  

    if linalg.det(xTx) == 0.0:  

        raise NameError("This matrix is singular, cannot do inverse")  

        ws = linalg.pinv(xTx)*(X.T*Y)  

    ws = xTx.I*(X.T*Y)  

    return ws, X, Y  

  

  

def modelLeaf(dataSet):             #当数据不再需要切分的时候它负责生成叶节点模型  

    ws, X, Y = linearSolve(dataSet)  

    return ws  

  

def modelErr(dataSet):                

    ws, X, Y = linearSolve(dataSet)  

    yHat     = X*ws  

    return sum(power(Y - yHat,2))       #计算平方误差  

  

myMat2 = mat(loadDataSet("exp2.txt"))  

 

用户评论

表情0/300

听友97465390

什么鬼

叮宕 回复 @听友97465390

鬼算不上,我是呆