简单的回归与预测 & matplotlib坐标轴设置参数(刻度值、间隔)

利用局部加权线性回归算法预测杭州西湖区房价趋势,通过分析2008年至2019年的房价数据,展示了房价的变化及预测结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《机器学习实战》第八章--机器学习分析西湖房价

8.2节讲到了局部加权线性回归,由于我们这里只有一个特征,因此输入X矩阵只有偏置常数(x0=1)和x1

楼主闲来无事,从网上down近几年西湖区的房价变化,结合课程中学到的算法,做了一些分析

# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 19:20:59 2018

@author: sjl
"""
import matplotlib.pyplot as plt
import numpy as np

def loadDataSet(fileName):      #general function to parse tab -delimited floats
    dataMat = []
    fr = open(fileName)
    for line in fr.readlines():
        curLine = line.split()
        dataMat.append(int(curLine[1]))
    return dataMat

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):                      #next 2 lines create weights matrix
        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 lwlrTest(testArr,xArr,yArr,k=1.0):  #loops over all the data points and applies lwlr to each one
    m = shape(testArr)[0]
    yHat = zeros(m)
    for i in range(m):
        yHat[i] = lwlr(testArr[i],xArr,yArr,k)
    return yHat


def made_mat(unit_0,unit_1,unit_2):
    dataMat=[]
    delta = unit_2-unit_1+1
    for i in range(delta):
        lineArr = []
        lineArr.append(float(unit_0))
        lineArr.append(unit_1+delta-i)
        dataMat.append(lineArr)
    return dataMat
   
xArr = made_mat(1.00000,1,115)
yArr=loadDataSet('house.txt')
yHat = lwlrTest(xArr,xArr,yArr,3)
xMat = mat(xArr)
srtInd =xMat[:,1].argsort(0)    #argsort返回从小到大排序后对应的索引值
xSort = xMat[srtInd][:,0,:]

xAdd = made_mat(1.00000,116,125)
yHatAdd = lwlrTest(xAdd,xArr,yArr,3)
xMatAdd = mat(xAdd)
srtIndAdd =xMatAdd[:,1].argsort(0)    #argsort返回从小到大排序后对应的索引值
xSortAdd = xMatAdd[srtIndAdd][:,0,:]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(xSort[:,1],yHat[srtInd],color='blue',linewidth=3.0,linestyle='-')
ax.plot(xSortAdd[:,1],yHatAdd[srtIndAdd],color='red',linewidth=3.0,linestyle='-')

ax.scatter(xMat[:,1].flatten().A[0],mat(yArr).T.flatten().A[0],s=2,c='red')

ax.axis([0,144,12000,55000])
plt.xlabel('Month(since 2008)')
plt.ylabel('Price')
year = [2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]
plt.xticks(np.arange(0,144,12),year)
plt.title('House Price in West Lake, Hangzhou')
plt.show()

house.txt内容如下:

2018年07月房价 38927 元/㎡5.72%↑
2018年06月房价 36822 元/㎡1.07%↑
2018年05月房价 36433 元/㎡--
2018年04月房价 35918 元/㎡0.42%↑
2018年03月房价 35770 元/㎡--
2018年02月房价 35551 元/㎡0.01%↓
2018年01月房价 35554 元/㎡0.02%↑
2017年12月房价 35549 元/㎡--
2017年11月房价 35278 元/㎡1.9%↑
2017年10月房价 34621 元/㎡0.05%↑
2017年09月房价 34023 元/㎡2.06%↑
2017年08月房价 33335 元/㎡0.79%↑
2017年07月房价 33073 元/㎡0.05%↑
2017年06月房价 32412 元/㎡0.49%↓
2017年05月房价 32571 元/㎡--
2017年04月房价 31843 元/㎡2.15%↑
2017年03月房价 31173 元/㎡0.15%↑
2017年02月房价 30075 元/㎡1.01%↑
2017年01月房价 29774 元/㎡10.39%↑
2016年12月房价 26972 元/㎡0.64%↓
2016年11月房价 27147 元/㎡5.41%↑
2016年10月房价 25753 元/㎡6.65%↑
2016年09月房价 24147 元/㎡1.74%↑
2016年08月房价 23734 元/㎡0.94%↑
2016年07月房价 23513 元/㎡0.05%↑
2016年06月房价 23501 元/㎡2.04%↑
2016年05月房价 23031 元/㎡0.86%↓
2016年04月房价 23231 元/㎡0.17%↓
2016年03月房价 23272 元/㎡2.25%↑
2016年02月房价 22760 元/㎡1.64%↑
2016年01月房价 22394 元/㎡0.02%↑
2015年12月房价 22389 元/㎡1%↓
2015年11月房价 22559 元/㎡2%↓
2015年10月房价 23057 元/㎡--
2015年09月房价 22964 元/㎡1%↑
2015年08月房价 22696 元/㎡1%↓
2015年07月房价 22831 元/㎡--
2015年06月房价 22881 元/㎡--
2015年05月房价 22861 元/㎡3%↑
2015年04月房价 22182 元/㎡--
2015年03月房价 22162 元/㎡1%↓
2015年02月房价 22305 元/㎡--
2015年01月房价 22245 元/㎡1%↓
2014年12月房价 22471 元/㎡0.33%↓
2014年11月房价 22546 元/㎡0.03%↑
2014年10月房价 22539 元/㎡2.11%↓
2014年09月房价 23025 元/㎡0.55%↑
2014年08月房价 22898 元/㎡0.07%↓
2014年07月房价 22913 元/㎡1.98%↓
2014年06月房价 23376 元/㎡0.71%↓
2014年05月房价 23544 元/㎡2.34%↓
2014年04月房价 24109 元/㎡1.33%↓
2014年03月房价 24434 元/㎡0.03%↓
2014年02月房价 24442 元/㎡0.22%↓
2014年01月房价 24495 元/㎡1.24%↓
2013年12月房价 24802 元/㎡0.14%↓
2013年11月房价 24836 元/㎡1.52%↓
2013年10月房价 25220 元/㎡0.99%↑
2013年09月房价 24972 元/㎡0.24%↑
2013年08月房价 24912 元/㎡1.1%↑
2013年07月房价 24640 元/㎡0.28%↑
2013年06月房价 24572 元/㎡0.16%↓
2013年05月房价 24612 元/㎡1.02%↓
2013年04月房价 24865 元/㎡0.74%↑
2013年03月房价 24683 元/㎡1.27%↑
2013年02月房价 24374 元/㎡0.15%↓
2013年01月房价 24410 元/㎡1.69%↑
2012年12月房价 24004 元/㎡1.5%↑
2012年11月房价 23650 元/㎡0.31%↓
2012年10月房价 23724 元/㎡0.22%↓
2012年09月房价 23777 元/㎡0.63%↑
2012年08月房价 23627 元/㎡0.1%↓
2012年07月房价 23650 元/㎡2.32%↑
2012年06月房价 23113 元/㎡1.31%↑
2012年05月房价 22814 元/㎡1.06%↓
2012年04月房价 23059 元/㎡0.64%↓
2012年03月房价 23208 元/㎡2%↑
2012年02月房价 22754 元/㎡1.63%↓
2012年01月房价 23132 元/㎡
2011年12月房价 23854 元/㎡3.22%↓
2011年11月房价 24647 元/㎡3.34%↓
2011年10月房价 25498 元/㎡2.09%↓
2011年09月房价 26042 元/㎡0.73%↑
2011年08月房价 25852 元/㎡0.21%↓
2011年07月房价 25906 元/㎡0.46%↑
2011年06月房价 25788 元/㎡0.14%↓
2011年05月房价 25825 元/㎡0.21%↓
2011年04月房价 25880 元/㎡0.17%↑
2011年03月房价 25835 元/㎡3.36%↑
2011年02月房价 24994 元/㎡2.05%↑
2011年01月房价 24491 元/㎡
2010年12月房价 24276 元/㎡0.6%↑
2010年11月房价 24132 元/㎡0.73%↑
2010年10月房价 23957 元/㎡1.35%↑
2010年09月房价 23639 元/㎡1.44%↑
2010年08月房价 23304 元/㎡1.07%↓
2010年07月房价 23555 元/㎡2.21%↓
2010年06月房价 24088 元/㎡0.25%↑
2010年05月房价 24027 元/㎡3.34%↑
2010年04月房价 23251 元/㎡9.03%↑
2010年03月房价 21325 元/㎡1.53%↑
2010年02月房价 21004 元/㎡0.58%↑
2010年01月房价 20882 元/㎡2.87%↑
2009年12月房价 20300 元/㎡5.59%↑
2009年11月房价 19225 元/㎡7.68%↑
2009年10月房价 17854 元/㎡4.41%↑
2009年09月房价 17100 元/㎡5.62%↑
2009年08月房价 16190 元/㎡4.73%↑
2009年07月房价 15459 元/㎡7.9%↑
2009年06月房价 14327 元/㎡4.41%↑
2009年05月房价 13722 元/㎡3.66%↑
2009年04月房价 13238 元/㎡2.21%↑
2009年03月房价 12952 元/㎡0.66%↓
2009年02月房价 13038 元/㎡1.89%↓
2009年01月房价 13289 元/㎡

结果如下:

代码中k是平滑参数,过小会过拟合,过大会欠拟合;

事实上,因为杭州房价因为G20过后疯涨,这次预测并没有实际意义,因为样本特征有80%是无关的,这告诉我们,数据集的选择要正确。

 

关于matplotlib的一些tips,看备注

fig = plt.figure()      #图片对象
ax = fig.add_subplot(111)
ax.plot(xSort[:,1],yHat[srtInd],color='blue',linewidth=3.0,linestyle='-')   #设置线1参数
ax.plot(xSortAdd[:,1],yHatAdd[srtIndAdd],color='red',linewidth=3.0,linestyle='-')

ax.scatter(xMat[:,1].flatten().A[0],mat(yArr).T.flatten().A[0],s=2,c='red')   #画散点

ax.axis([0,144,12000,55000])      #画轴的范围
plt.xlabel('Month(since 2008)')   #x轴标签
plt.ylabel('Price')               #y轴标签
year = [2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]
plt.xticks(np.arange(0,144,12),year)     #重新设置x轴间隔和刻度值
plt.title('House Price in West Lake, Hangzhou')    #标题
plt.show()          #画图

 

<think>好的,用户现在的问题是如何在Matplotlib的二维平面图中绘制x和y。之前用户询问的是关于3D PCA加载图的绘制,现在转向了更基础的二维坐标轴绘制。需要结合用户提供的引用内容,尤其是引用[1]中提到的Matplotlib基础知识,比如坐标轴设置刻度调整等。首先,用户可能刚接触Matplotlib,需要最基础的指导。需要分步骤讲解如何创建图形、添加坐标轴,并确保每个步骤的代码示例清晰。同时,用户提供的引用里提到设置坐标轴颜色、标题大小、刻度参数等,这些可以作为补充内容,让回答更全面。 要检查用户是否有特殊需求,比如是否要自定义的外观,或者绘制特定的图形。但根据问题描述,用户主要想知道如何绘制二维的x和y,可能包括坐标轴的显示、标签、刻度等基本元素。需要确保代码示例正确,比如使用plt.gca()获取当前坐标轴,或者通过plt.subplots()创建。同时,引用中的ax.tick_params方法可以用来设置刻度样式,这也应该包含在回答中,作为自定义坐标轴的一部分。 另外,用户之前的问题涉及回归和PCA,可能有一定的数据分析背景,因此可以适当提及坐标轴在数据可视化中的应用,但当前问题主要集中在绘图基础,需要保持回答的针对性。最后,生成相关问题时要围绕二维绘图,可能涉及样式调整、应用场景、高级设置等,帮助用户进一步学习。</think>### 二维平面图坐标轴绘制指南 --- #### 一、基础绘制方法 ##### 步骤1:创建基本坐标系 ```python import matplotlib.pyplot as plt # 创建空白画布 plt.figure(figsize=(8, 6)) # 设置画布尺寸[^1] # 自动生成坐标轴系统 ax = plt.gca() # 获取当前坐标轴 plt.plot([], []) # 绘制空数据曲线 plt.show() ``` 此时将显示包含x和y的空白坐标系,刻度范围默认为$[0,1]$ ##### 步骤2:设置坐标轴范围 ```python plt.xlim(-5, 5) # 设置x范围 plt.ylim(-10, 10) # 设置y范围 plt.grid(True) # 显示网格[^1] ``` --- #### 二、坐标轴定制化 ##### 1. 标签设置 ```python plt.xlabel("X Axis", fontsize=12, color='blue', fontweight='bold') plt.ylabel("Y Axis", rotation=90, style='italic') ``` ##### 2. 刻度参数调整 ```python ax.tick_params(axis='both', direction='inout', # 刻度线方向 length=8, # 刻度线长度 width=2, # 刻度线宽度 colors='green', # 刻度颜色 labelsize=10) # 标签字号[^1] ``` ##### 3. 数学表达式支持 ```python plt.title(r'$\frac{\sin(x)}{x}$ 函数曲线') # 使用LaTeX公式 plt.xlabel(r'$\theta$ (rad)') ``` --- #### 三、完整示例 ```python import numpy as np x = np.linspace(-np.pi, np.pi, 100) y = np.sin(x)/x plt.figure(figsize=(10, 6)) plt.plot(x, y, color='red', linewidth=2) # 坐标轴设置 plt.axhline(0, color='black', linewidth=1) # 绘制x plt.axvline(0, color='black', linewidth=1) # 绘制y plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', '0', r'$\pi/2$', r'$\pi$']) plt.yticks([-0.5, 0, 0.5, 1]) plt.grid(linestyle='--', alpha=0.6) plt.show() ``` --- #### 四、坐标轴数学原理 二维坐标系中,任意点位置由坐标对$(x,y)$确定。设画布尺寸为$W \times H$,则坐标转换公式为: $$ x_{pixel} = \frac{x - x_{min}}{x_{max} - x_{min}} \times W $$ $$ y_{pixel} = H - \frac{y - y_{min}}{y_{max} - y_{min}} \times H $$ --- #### 五、常见问题解决方案 | 问题现象 | 解决方法 | |---------|----------| | 坐标轴显示不全 | 调整`plt.margins(0.1)`设置边距 | | 刻度标签重叠 | 使用`plt.xticks(rotation=45)`旋转标签[^1] | | 科学计数法显示 | 设置`ax.ticklabel_format(style='plain')` | | 双坐标轴系统 | 创建次坐标轴:`ax.secondary_xaxis()` | --- ### 相关问题 1. 如何绘制带箭头的坐标轴? 2. 怎样设置对数坐标轴? 3. 如何隐藏特定边的坐标轴? 4. 坐标轴刻度间隔的自动优化方法? 5. 不同子图之间如何同步坐标轴范围?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yanjing-233

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值