import numpy as np
import matplotlib.pyplot as plt
#n列数据,最后一列是结果
def loadDataSet(filename):
numFeat = len(open(filename).readline().split('\t')) - 1
dataMat, labelMat = [], []
fr = open(filename)
for line in fr.readlines():
LineArr = []
curlLine = line.strip().split('\t')
for i in range(numFeat):
LineArr.append(float(curlLine[i]))
dataMat.append(LineArr)
labelMat.append(float(curlLine[-1]))
return dataMat, labelMat
def standRegress(xArr, yArr):
# x,y变成矩阵形式 y 应为竖着的形式
xMat ,yMat= np.mat(xArr), np.mat(yArr).T
xTx = xMat.T*xMat
# linear algorithm
if np.linalg.det(xTx) == 0:
return
ws = xTx.I * (xMat.T*yMat)
return ws
xArr, yArr = loadDataSet('ex0.txt')
ws = np.array(standRegress(xArr, yArr))
ws = [x for sublist in ws for x in sublist]
print(ws)
plt.figure()
## list是不能用[:,1]索引的,array可以
plt.scatter(np.array(xArr)[:, 1], np.array(yArr)[:])
x = np.arange(0, 1, 0.02)
y = ws[0] + ws[1]*x
plt.plot(x, y)
plt.show()