一个小知识为:
在同一张图上显示两个不同的函数:
只需要在ax = scatter()的基础上
ax = plt.plot(x,y) 即可
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def standRegres(xArr,yArr):
xMat = np.mat(xArr)
yMat = np.mat(yArr).T
xTx = xMat.T *xMat
if(np.linalg.det(xTx)) ==0.0:
print("这个矩阵没有逆,则无法求解线性回归")
return
ws = xTx.I * (xMat.T*yMat)
return ws
def loadDataSet(filename):
numFeat = len(open(filename).readline().split('\t')) - 1
dataMat = []
lableMat = []
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)
lableMat.append(float(curline[-1]))
return dataMat,lableMat
def drawpictrue(xArr,yArr):
xdatingMat = []
for i in range(len(xArr)):
xdatingMat.append([xArr[i][1],yArr[i]])
datingMat = np.array(xdatingMat)
fig = plt.figure(0)
ax = fig.add_subplot(111)
ax.scatter(datingMat[:,0],datingMat[:,1])
ws = standRegres(xArr,yArr)
xMat = np.mat(xArr)
yMat = np.mat(yArr)
yHat = xMat*ws
xCopy = xMat.copy()
xCopy.sort(0)
yHat = xCopy*ws
ax = plt.plot(xCopy[:,1],yHat)
plt.show()