#利用局部加权线性回归函数,对数据集xArr中的每一个样本点进行预测,并绘制预测折线图与原数据散点图的叠加图 #step1:绘制原数据散点图 xArr,yArr = loadDataSet('ex0.txt') plt.scatter(array(xArr)[:,1],array(yArr)) #step2: 绘制拟合线(局部加权线性回归)
时间: 2024-02-25 21:57:11 浏览: 33
以下是利用局部加权线性回归函数对数据集xArr中的每一个样本点进行预测,并绘制预测折线图与原数据散点图的叠加图的代码:
```python
import matplotlib.pyplot as plt
from numpy import *
# 加载数据函数
def loadDataSet(fileName):
numFeat = len(open(fileName).readline().split('\t')) - 1
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]))
return dataMat,labelMat
# 局部加权线性回归函数
def lwlr(testPoint,xArr,yArr,k=1.0):
xMat = mat(xArr); yMat = mat(yArr).T
m = shape(xMat)[0]
weights = mat(eye((m)))
for j in range(m):
diffMat = testPoint - xMat[j,:]
weights[j,j] = exp(diffMat*diffMat.T/(-2.0*k**2))
xTx = xMat.T * (weights * xMat)
if linalg.det(xTx) == 0.0:
print("This matrix is singular, cannot do inverse")
return
ws = xTx.I * (xMat.T * (weights * yMat))
return testPoint * ws
# 绘制预测折线图与原数据散点图的叠加图函数
def plotLWLR(xArr,yArr,k=1.0):
xMat = mat(xArr); yMat = mat(yArr)
yHat = zeros(shape(yArr)) # 预测值初始化为0
# 循环每个样本点,进行局部加权线性回归预测
for i in range(shape(xMat)[0]):
yHat[i] = lwlr(xMat[i],xArr,yArr,k)
# 绘制原数据散点图
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(xMat[:,1].flatten().A[0], yMat.T[:,0].flatten().A[0], s=2, c='red')
# 绘制预测折线图
srtInd = xMat[:,1].argsort(0)
xSort = xMat[srtInd][:,0,:]
ax.plot(xSort[:,1], yHat[srtInd], c='blue')
plt.show()
# 测试绘制预测折线图与原数据散点图的叠加图函数
xArr,yArr = loadDataSet('ex0.txt') # 加载数据
plotLWLR(xArr,yArr,k=0.01) # 绘制预测折线图与原数据散点图的叠加图
```
运行以上代码,即可绘制出预测折线图与原数据散点图的叠加图。其中,局部加权线性回归函数lwlr用于对每个样本点进行预测,plotLWLR函数用于绘制预测折线图与原数据散点图的叠加图。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)