xMat = mat(xArr) yMat = mat(yArr).T xTx = xMat.T * xMat if np.linalg.det(xTx) == 0.0: print('This matrix is singular, cannot do inverse') return None ws = xTx.I * (xMat.T * yMat) return ws if __name__ == '__main__': from a1_loadDataSet import loadDataSet import matplotlib.pyplot as plt filename = 'data/ex0.txt' dataMat, labelMat = loadDataSet(filename) print(dataMat) print(labelMat) ws = standRegres(dataMat, labelMat) print(ws) xMat = mat(dataMat) yMat = mat(labelMat) yHat = xMat * ws fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(xMat[:, 1].flatten().A[0], yMat.T[:, 0].flatten().A[0]) xCopy = xMat.copy() xCopy.sort(0) yHatp = xCopy * ws ax.plot(xCopy[:, 1], yHatp)
def lwlrTest(testArr, xArr, yArr, k=1.0): m = shape(testArr)[0] yHat = zeros(m) for i in range(m): yHat[i] = lwlr(testArr[i], xArr, yArr, k) return yHat if __name__ == '__main__': from a1_loadDataSet import loadDataSet filename = 'data/ex0.txt' xArr, yArr = loadDataSet(filename) print(xArr) print(yArr) print(yArr[0]) print(lwlr(xArr[0], xArr, yArr, 1.0)) print(lwlr(xArr[0], xArr, yArr, 0.01)) yHat = lwlrTest(xArr, xArr, yArr, 0.01) xMat = mat(xArr) srtInd = xMat[:, 1].argsort(0) xSort = xMat[srtInd][:, 0, :] import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.plot(xSort[:, 1], yHat[srtInd])
@ Freshield @ @==============================================@ """ from numpy import * def rssError(yArr, yHatArr): return ((yArr-yHatArr)**2).sum() if __name__ == '__main__': from a1_loadDataSet import loadDataSet from a2_standRegres import standRegres from a3_lwlr import lwlrTest filename = 'data/abalone.txt' abX, abY = loadDataSet(filename) yHat01 = lwlrTest(abX[:99], abX[:99], abY[:99], 0.1) yHat1 = lwlrTest(abX[:99], abX[:99], abY[:99], 1) yHat10 = lwlrTest(abX[:99], abX[:99], abY[:99], 10) print(rssError(abY[:99], yHat01.T)) print(rssError(abY[:99], yHat1.T)) print(rssError(abY[:99], yHat10.T)) yHat01 = lwlrTest(abX[100:199], abX[:99], abY[:99], 0.1) yHat1 = lwlrTest(abX[100:199], abX[:99], abY[:99], 1) yHat10 = lwlrTest(abX[100:199], abX[:99], abY[:99], 10) print(rssError(abY[100:199], yHat01.T)) print(rssError(abY[100:199], yHat1.T)) print(rssError(abY[100:199], yHat10.T)) ws = standRegres(abX[:99], abY[:99]) yHat = mat(abX[100:199]) * ws