09 ML standard regression

1.png

來自: https://github.com/start-program/machinelearninginaction/blob/master/Ch08/regression.py

from numpy import *
import matplotlib.pyplot as plt

def loadDataSet(fileName):      #general function to parse tab -delimited floats
    numFeat = len(open(fileName).readline().split('\t')) - 1 #get number of fields 
    dataMat = []
    labelMat = []

    fr = open(fileName)
    for line in fr.readlines():
        lineArr =[]
        curLine = line.strip().split('\t')
        for i in range(numFeat):
            lineArr.append(float(curLine[i]))
        dataMat.append(lineArr)
        labelMat.append(float(curLine[-1])) # last is label
    return dataMat,labelMat

def standRegres(xArr,yArr):
    xMat = mat(xArr)
    yMat = mat(yArr).T

    xTx = xMat.T*xMat

    if linalg.det(xTx) == 0.0:
        print "This matrix is singular, cannot do inverse"
        return

    ws = xTx.I * (xMat.T*yMat) # calc ws
    return ws

xArr, yArr = loadDataSet('ex0.txt')
print('xArr', xArr[0:2])
print('yArr', yArr[0:2])

ws = standRegres(xArr, yArr)
print('ws', ws)

xMat = mat(xArr) # 2 dimension array to matrix
yMat = mat(yArr)

print('xMat', xMat[0:2])

fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(xMat[:, 1].flatten().A[0], yMat.T[:, 0].flatten().A[0]) # scatter plot

xCopy = xMat.copy()
xCopy.sort(0)

yHat = xCopy * ws # calc y
ax.plot(xCopy[:, 1], yHat) # draw y line
plt.show()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容