首先导入库并避免显示错误FutureWorning

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
from sklearn import preprocessing
import warningswarnings.filterwarnings("ignore")  # 避免显示FutureWorning

预处理数据并筛选相关系数较大的特征值
注释的第一部分:为显示各个影响因素与价格的关系图
注释的第二部分:通过一元线性回归,将筛选的三个相关系数最大的特征值与价格的关系图绘制出来

boston = load_boston()
x = boston['data']  # 所有特征信息
y = boston['target']  # 房价
feature_names = boston['feature_names']  # 十三个影响因素
boston_data = pd.DataFrame(x, columns=feature_names)  # 特征信息和影响因素
boston_data['price'] = y  # 添加价格列
'''
for i in range(13):plt.figure(figsize=(10, 7))plt.scatter(x[:,i],y,s=2)#某影响因素的特征信息与房价plt.title(feature_names[i])
plt.show()'''
cor = boston_data.corr()['price']  # 求取相关系数
print(cor)
# 取相关系数大于0.5的特征值 RM LSTAT PTRATIO priceboston_data = boston_data[['LSTAT', 'PTRATIO', 'RM', 'price']]  # 保留该四组因素
y = np.array(boston_data['price'])
feature_names = ['LSTAT', 'PTRATIO', 'RM', 'price']
'''
for i in range(3):x = np.array(boston_data[feature_names[i]])var = np.var(x,ddof=1)cov = np.cov(x,y)[0][1]k = cov/varb = np.mean(y) - k*np.mean(x)y_price = k*x + bplt.plot(x,y,'b.')plt.plot(x,y_price,'k-')plt.show()'''

—————————————————————————————————————————————

使用模型求解

通过LinearRegression库直接实现

boston_data = boston_data.drop(['price'], axis=1)
x = np.array(boston_data)
print(x)
train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.3, random_state=0)  # 分割训练集和测试集# 直接使用模型求解
# 加载模型
li = LinearRegression()
# 拟合数据
li.fit(train_x, train_y)
# 进行预测
y_predict = li.predict(test_x)
plt.figure(figsize=(10, 7))
plt.plot(y_predict, 'b-')
plt.plot(test_y, 'r--')
plt.legend(['predict', 'true'])
plt.title('Module')
plt.show()
mes = metrics.mean_squared_error(y_predict, test_y)
print(mes)

—————————————————————————————————————————————

最小二乘法求解

对系数B矩阵求偏导,偏导为0时,即为目标解

boston_data.insert(loc=0, column='one', value=1)
print(boston_data)
x = np.array(boston_data)
train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.3, random_state=0)  # 分割训练集和测试集
xT = x.T
x_mat = np.mat(train_x)
y_mat = np.mat(train_y).T
xT = x_mat.T
B = (xT * x_mat).I * xT * y_mat
print(B)
y_predict = test_x * B
plt2 = plt.figure(figsize=(10, 7))
plt2 = plt.plot(y_predict, 'b-')
plt2 = plt.plot(test_y, 'r--')
plt2 = plt.legend(['predict', 'true'])
plt2 = plt.title('Least Sqaure Method')
plt.show()
# [[22.17686885]
# [-0.55760828]
# [-1.11165635]
# [ 4.44512502]]

—————————————————————————————————————————————

多元线性回归

简单多元线性回归(梯度下降算法与矩阵法)
机器学习方法之线性回归(LR)

首先处理x中的数据,在x每一行前添加1

print(boston_data)
x = np.array(boston_data)
train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.3, random_state=0)  # 分割训练集和测试集
xT = x.T
print(xT)
x_mat = np.mat(train_x)
y_mat = np.mat(train_y).T
xT = x_mat.T
B = [[22.1768],[-0.5576],[-1.11165],[4.44512]]
B = np.mat(B)
Bp = -2*xT*(y_mat-x_mat*B) # 即B的偏导
while 1:B = B - 0.000005*BpBp = -2 * xT * (y_mat - x_mat * B)for i in range(4):sum = 0sum += abs(Bp[i])print(sum)if sum <=0.00001: breakprint(B)
print("最终B:",B)
# 最终B: [[22.17682455]
#   [-0.55760809]
#  [-1.11165553]
#  [ 4.44512921]]
y_predict = test_x*B
plt3 = plt.figure(figsize=(10, 7))
plt3 = plt.plot(y_predict,'b-')
plt3 = plt.plot(test_y,'r--')
plt3 = plt.legend(['predict', 'true'])
plt.title('Multiple Linear Regression')
plt.show()

波士顿房价的三种预测方式(模型预测,最小二乘法,多元线性回归)相关推荐

  1. ML之FE:基于波士顿房价数据集利用LightGBM算法进行模型预测然后通过3σ原则法(计算残差标准差)寻找测试集中的异常值/异常样本

    ML之FE:基于波士顿房价数据集利用LightGBM算法进行模型预测然后通过3σ原则法(计算残差标准差)寻找测试集中的异常值/异常样本 目录 基于波士顿房价数据集利用LiR和LightGBM算法进行模 ...

  2. Django09:图书管理系统笔记/choices用法/ MTV与MVC模型/多对多三种创建方式

    图书管理系统笔记 redirect括号内可以直接写url 也可以直接写别名 但如果别名需要参数,必须使用reverse解析. choices用法 使用场景:能列举完全的数据 #使用方法:xxx_cho ...

  3. Django 数据库查询优化,choices参数(数据库字段设计常见),MVC和MTV模型,多对多三种创建方式...

    数据库查询优化 orm语句的特点:惰性查询 如果仅仅只是书写了orm语句,在后面没有用到该语句所查询出来的参数,那么orm会自动识别,并不执行 举例: res = models.Book.object ...

  4. css样式 三种引入方式 选择器 常用属性:背景属性 字体属性 边框属性 内间距 外间距 盒子模型

    一.CSS简介 1.什么是css 重叠样式表 主要是负责标签的样式 美化页面 一个网页分三大部分 结构层: 主要由html负责 负责页面的结构 表现层: 主要由css负责 页面的展示样式 美化页面 行 ...

  5. Web框架之Django_07 进阶操作(MTV与MVC、多对多表三种创建方式、前后端传输数据编码格式contentType、ajax、自定义分页器)

    阅读目录 一.MVC与MTV 二.多对多表的创建 三.ajax,前后端传输编码格式contentType 四.批量插入数据与自定义分页器 摘要 MTV与MVC 多对多表三种创建方式 ajax ,前后端 ...

  6. EF三种编程方式详细图文教程(C#+EF)之Database First

    Entity Framework4.1之前EF支持"Database First"和"Model First"编程方式,从EF4.1开始EF开始支持支持&quo ...

  7. iDesktop点数据集构建DEM时三种插值方式的选择

    转自:https://blog.csdn.net/supermapsupport/article/details/76252498 点数据构建DEM的时候,可以选择三种插值方式,分别是不规则三角网法, ...

  8. linux内核 struct page结构的三种存放方式

    目录 page struct的三种存放方式 1) FLATMEM 2) SPARSEMEM 3) SPARSEMEM_VMEMMAP 随着硬件能力的提升,系统内存容量变得越来越大.尤其是在服务器上,过 ...

  9. (转)EF三种编程方式详细图文教程(C#+EF)之Database First

    Entity Framework4.1之前EF支持"Database First"和"Model First"编程方式,从EF4.1开始EF开始支持支持&quo ...

最新文章

  1. LeetCode 15三数之和16最接近的三数之和
  2. 多播程序设计(基于UDP协议)
  3. redis文档翻译_key设置过期时间
  4. 阿里云服务器一分价钱一分货,切记!
  5. Flutter AnimatedBuilder 的基本使用
  6. 面试了一个 35+ 岁的大佬,一言难尽......
  7. JS开发之Factory(工厂)模式解析
  8. Hyperledger Fabric教程(15)--基于Kafka的Order服务实战
  9. 奔驰北京工厂两年内将再投产三款电动车;希尔顿中国市场第300家酒店开业 | 美通企业日报...
  10. libtersafe文件下载_tersafe.dll官方版下载
  11. Vue搭脚手架及创建项目
  12. 初步设计对复杂系统的意义
  13. 解锁中智集团30平方米数据中心备受追捧的密码
  14. Building the main Guest Additions module [failed]
  15. 室外定位--GPS定位概述
  16. python pil grab screen
  17. 完整简洁的Oracle获得汉字字符串拼音首字母和全拼的函数
  18. 应用MapX编程两例
  19. Mybatis-原理总结
  20. 2019长沙学院新生赛(A水,B水,C(整除分块),D水,E(巧数学),F(二分+bfs),H(换根dp),I(线段树)J(dp+倍增+lca))

热门文章

  1. Prometheus 服务发现
  2. Android水平渐变色圆角矩形
  3. 成都5日--成都-都江堰-青城山-西岭雪山1116
  4. python实现批量移动文件到指定文件夹
  5. 高中网络技术应用计算机病毒教案,信息安全和保护高中信息技术教案
  6. 利用GAE+WallProxy-plugins搭建个人代理服务器
  7. 云平台是什么意思 云服务平台有哪些【详细介绍】
  8. 猿辅导服务端开发面试--秋招正式批
  9. sql语句like的用法
  10. ItemCreated和ItemDataBound事件的区别