模型樹
觀察下圖的數(shù)據(jù)分布,很容易發(fā)現(xiàn)可以用兩條直線來擬合數(shù)據(jù)拒逮,0.0 ~ 0.3是一條直線,0.3 ~ 1.0是一條直線,可以得到兩個線性模型彩倚,這就是所謂的分段線性模型。
可以用樹生成算法對數(shù)據(jù)進行切分扶平,然后將線性模型保存在葉節(jié)點帆离。
回顧樹回歸(一)的createTree()
函數(shù),里面有兩個參數(shù)leafType
和errType
還沒有改變過结澄。這里略作修改哥谷,就可以實現(xiàn)模型樹。
def linearSolve(dataSet):
m,n = dataSet.shape
X = np.mat(np.ones((m,n)))
Y = np.mat(np.ones((m,1)))
X[:, 1:n] = dataSet[:, 0:n-1]
Y = dataSet[:, -1]
xTx = X.T * X
if np.linalg.det(xTx) == 0:
raise NameError('This matrix is singular, cannot do inverse,\n\
try increasing the second value of ops')
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(np.power(Y - yHat, 2))
linearSolve()
函數(shù)主要功能是將數(shù)據(jù)集格式化成目標(biāo)變量Y和自變量X麻献,并計算系數(shù)们妥。
modelLeaf()
與regLeaf()
類似,這里是負責(zé)生成葉節(jié)點的模型勉吻。
modelErr()
與regErr()
類似监婶,用于計算誤差。
到這里,模型樹的構(gòu)建代碼就完成了惑惶。只需要將參數(shù)換成modelLeaf
和modelErr
就可以了煮盼。
myMat = np.mat(loadDataSet('exp2.txt'))
createTree(myMat, modelLeaf, modelErr, (1, 10))
運行結(jié)果如下:
{'spInd': 0, 'spVal': 0.285477, 'left': matrix([[1.69855694e-03],
[1.19647739e+01]]), 'right': matrix([[3.46877936],
[1.18521743]])}
下面看一下擬合效果。
import matplotlib.pyplot as plt
import numpy as np
# 構(gòu)建模型樹
myMat = np.mat(loadDataSet('exp2.txt'))
modelTree = createTree(myMat, modelLeaf, modelErr, (1, 10))
X = np.linspace(0, 1, num=100)
# 直線1
ws1 = modelTree['left']
Y1 = X * float(ws1[1]) + float(ws1[0])
# 直線2
ws2 = modelTree['right']
Y2 = X * float(ws2[1]) + float(ws2[0])
plt.scatter(myMat[:,0].T.tolist()[0], myMat[:,1].T.tolist()[0])
plt.plot(X, Y1, color = 'red')
plt.plot(X, Y2, color = 'yellow')
plt.show()
結(jié)果如下
可以看到兩條直線都很好的擬合數(shù)據(jù)带污,并且模型樹的切分點0.285477也很符合數(shù)據(jù)的實際情況僵控。
樹回歸與標(biāo)準(zhǔn)回歸的比較
接下來將用一份非線性的數(shù)據(jù)測試模型樹、回歸樹和一般的回歸方法鱼冀,比較哪個最好报破。
# 回歸樹預(yù)測方法
def regTreeEval(model, inDat):
return float(model)
# 模型樹預(yù)測方法
def modelTreeEval(model, inDat):
n = inDat.shape[1]
X = np.mat(np.ones((1, n+1)))
X[:, 1:n+1] = inDat
return float(X*model)
def treeForeCast(tree, inData, modelEval = regTreeEval):
if not isTree(tree):
return modelEval(tree, inData)
if inData[tree['spInd']] > tree['spVal']:
if isTree(tree['left']):
return treeForeCast(tree['left'], inData, modelEval)
else:
return modelEval(tree['left'], inData)
else:
if isTree(tree['right']):
return treeForeCast(tree['right'], inData, modelEval)
else:
return modelEval(tree['right'], inData)
def createForeCast(tree, testData, modelEval=regTreeEval):
m = len(testData)
yHat = np.mat(np.zeros((m,1)))
for i in range(m):
yHat[i, 0] = treeForeCast(tree, np.mat(testData[i]), modelEval)
return yHat
用到的數(shù)據(jù)集的數(shù)據(jù)分布如下。
# 加載數(shù)據(jù)集
trainMat = np.mat(loadDataSet('bikeSpeedVsIq_train.txt'))
testMat = np.mat(loadDataSet('bikeSpeedVsIq_test.txt'))
# 構(gòu)建回歸樹
regTree = createTree(trainMat, ops=(1,20))
# 預(yù)測
regHat = createForeCast(regTree, testMat[:,0])
# 計算相關(guān)系數(shù)
np.corrcoef(regHat, testMat[:,1], rowvar=0)[0,1]
結(jié)果為0.964
千绪。
# 構(gòu)建模型樹
modelTree = createTree(trainMat, modelLeaf, modelErr, ops=(1,20))
# 預(yù)測
modelHat = createForeCast(modelTree, testMat[:,0], modelTreeEval)
# 計算相關(guān)系數(shù)
np.corrcoef(modelHat, testMat[:,1], rowvar=0)[0,1]
結(jié)果為0.976
泛烙。
從上面的結(jié)果來看,模型樹的效果要比回歸樹好翘紊。接下來看看一般的線性回歸效果如何蔽氨。
simpleRegHat = np.mat(np.zeros((testMat.shape[0],1)))
ws, X, Y = linearSolve(trainMat)
for i in range(testMat.shape[0]):
simpleRegHat[i] = testMat[i,0]*ws[1,0] + ws[0,0]
np.corrcoef(simpleRegHat, testMat[:,1], rowvar=0)[0,1]
這里用前面已經(jīng)實現(xiàn)的linearSolve()
函數(shù)來求解線性方程。然后循環(huán)計算預(yù)測值帆疟,最后計算得到的相關(guān)系數(shù)為0.943
鹉究。
可以看到,該方法不如前面兩種樹回歸方法踪宠。所以自赔,樹回歸方法在預(yù)測復(fù)雜數(shù)據(jù)時會比簡單的線性模型要更有效。