python数据挖掘课程】十八.线性回归及多项式回归分析四个案例分享
#2018-03-30 18:24:56 March Friday the 13 week, the 089 day SZ SSMR1.线性回归预测Pizza价格案例2.线性回归分析波士顿房价案例3.随机数据集一元线性回归分析和三维回归分析案例4.Pizza数据集一元线性回归和多元线性回归分析一. 线性回归预测Pizza价格案例
1.数据集介绍本章主要使用线性回归预测Pizza的价格,由于直径大小不同的Pizza,其价格也是不同的
2.线性回归分析线性回归基础步骤主要包括:1.导入数据集,采用列表的形式定义直接和价格两列数据。2.调用Scikit-learn机器学习包中线性回归模型。3.调用fit()函数对直径和价格进行训练。4.调用predice()函数对数据集进行预测。5.对线性回归算法进行评价。6.可视化分析并绘制相关图形,直观的呈现算法模型的结果。
线性回归分析的完整代码如下:
# -*- coding: utf-8 -*-
from sklearn.linear_model import LinearRegression#数据集 直径、价格
x = [[5],[6],[7],[8],[10],[11],[13],[14],[16],[18]]
y = [[6],[7.5],[8.6],[9],[12],[13.6],[15.8],[18.5],[19.2],[20]]clf = LinearRegression()
clf.fit(x,y)                #fit()函数用来分析模型参数
pre = clf.predict([12][0])  #predict()通过fit()算出模型参数构成的模型,对解释变量进行预测获得其结果
print(u'预测直径为12英寸的价格: $%.2f' % pre)3.可视化分析接下来需要对数据集进行可视化分析,首先需要调用Matplotlib扩展包绘制直径和价格的散点图,代码如下:
# -*- coding: utf-8 -*-
from sklearn.linear_model import LinearRegression#数据集 直径、价格
x = [[5],[6],[7],[8],[10],[11],[13],[14],[16],[18]]
y = [[6],[7.5],[8.6],[9],[12],[13.6],[15.8],[18.5],[19.2],[20]]clf = LinearRegression()
clf.fit(x,y)                #fit()函数用来分析模型参数
pre = clf.predict([12][0])  #predict()通过fit()算出模型参数构成的模型,对解释变量进行预测获得其结果
print(u'预测直径为12英寸的价格: $%.2f' % pre)x2 = [[0],[12],[15],[25]]
y2 = clf.predict(x2)
print(y2)
import matplotlib.pyplot as plt
plt.figure()
plt.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体
plt.title(u"线性回归预测Pizza直径和价格")
plt.xlabel(u"x")
plt.ylabel(u"price")
plt.axis([0,25,0,25])
plt.scatter(x,y,marker="s",s=20) #画散点图
plt.plot(x2,y2,"g-") #画直线
plt.show()二. 线性回归分析波士顿房价案例
Sklearn机器学习包中已经自带了该数据集,故直接引用该数据集,获取其中某两列数据.在做数据分析过程中,通常需要将数据集划分为训练集和预测集,这里作者将前406行作为训练集,最后100行作为预测集,划分代码如下:
# -*- coding: utf-8 -*-
#导入数据集boston
from sklearn.datasets import load_boston
import numpy as np
boston = load_boston()
print(boston.data.shape, boston.target.shape)
print (boston.data[10])
print ("boston.data is :",len(boston.data))print (boston.target)
print ("boston.target is:",len(boston.target))#划分数据集
boston_temp = boston.data[:, np.newaxis, 5]
x_train = boston_temp[:-100]      #训练样本
x_test = boston_temp[-100:]       #测试样本 后100行
y_train = boston.target[:-100]    #训练标记
y_test = boston.target[-100:]     #预测对比标记2.线性回归分析
线性回归过程主要如下:1.导入数据集,波士顿房价数据。2.划分数据集为训练集和测试集,采用406和100的比例。3.导入线性回归模型LinearRegression。4.对训练集进行训练操作,同时预测数据集结果。5.可视化画图分析及结果评估。线性回归分析波士顿房价数据集的代码如下:
# -*- coding: utf-8 -*-
#导入数据集boston
from sklearn.datasets import load_boston
import numpy as np
boston = load_boston()
print(boston.data.shape, boston.target.shape)
print (boston.data[10])
print ("boston.data is :",len(boston.data))#print (boston.target)
print ("boston.target is:",len(boston.target))
#划分数据集
boston_temp = boston.data[:, np.newaxis, 5]
x_train = boston_temp[:-100]      #训练样本
x_test = boston_temp[-100:]       #测试样本 后100行
y_train = boston.target[:-100]    #训练标记
y_test = boston.target[-100:]     #预测对比标记from sklearn.linear_model import LinearRegression
clf = LinearRegression()
clf.fit(x_train, y_train)  #算法评估
pre = clf.predict(x_test)
print (u"预测结果", pre)
print (u"真实结果", y_test)
cost = np.mean(y_test-pre)**2
print (u'平方和计算:', cost)
print (u'系数', clf.coef_   )
print (u'截距', clf.intercept_)
print (u'方差', clf.score(x_test, y_test) )#绘图分析
import matplotlib.pyplot  as plt
plt.title(u'LinearRegression Boston')
plt.xlabel(u'x')
plt.ylabel(u'price')
plt.scatter(x_test, y_test, color = 'black')
plt.plot(x_test, clf.predict(x_test), color='blue', linewidth = 3)
'''
for idx, m in enumerate(x_test):  plt.plot([m, m],[y_test[idx],pre[idx]], 'r-')    '''
plt.show()   三. 随机数据集线性回归分析和三维回归分析案例1.随机数据集
随机数生成主要调用Numpy扩展包中的random函数或arange,调用函数arange(0,50,0.2)实现,随机生成0到50个数据,其间隔为0.2。
得到X数据集之后,作者随机定义一个函数绘制对应的Y坐标,再调用Matplotlib扩展包可以对数据集进行可视化分析,并绘制相关的散点图。核心代码如下:
import numpy as np
import math
X =  np.arange(0,50,0.2)
print (X)
xArr = []
yArr = []
for n in X:xArr.append(n)y = 0.7*n + np.random.uniform(0,1)*math.sin(n)*2 - 3yArr.append(y)import matplotlib.pyplot as plt
plt.plot(xArr, yArr, 'go')plt.show()接下来需要调用Sklearn机器学习扩展包相关函数进行线性回归分析。2.线性回归
完整代码如下:
import numpy as np
import math
X =  np.arange(0,50,0.2)
print (X)
xArr = []
yArr = []
for n in X:xArr.append(n)y = 0.7*n + np.random.uniform(0,1)*math.sin(n)*2 - 3yArr.append(y)
'''
import matplotlib.pyplot as plt
plt.plot(xArr, yArr, '*')plt.show()
'''#线性回归分析
from sklearn.linear_model import LinearRegression
clf = LinearRegression()
print (clf)
X =  np.array(X).reshape((len(X),1))     #list列表转化为数组
print('X is:',X)
yArr = np.array(yArr).reshape((len(X),1))
clf.fit(X,yArr) #输入为数组
pre = clf.predict(X)import matplotlib.pyplot as plt
plt.plot(X, yArr, 'go')
plt.plot(X, pre, 'r', linewidth=3)
plt.show()补充一段3D绘制的代码,随机坐标生成后,需要调用mpl_toolkits.mplot3d子类中Axes3D类生成对应的3D图形。
代码:
# -*- coding: utf-8 -*-
import numpy as np
from sklearn import linear_model
from mpl_toolkits.mplot3d import Axes3D   #3D画图模块
import matplotlib.pyplot as plt
import math#linspace:开始值、终值和元素个数创建表示等差数列的一维数组
xx, yy = np.meshgrid(np.linspace(0,10,20), np.linspace(0,100,20))
print("np.linspace(0,10,20 is :",np.linspace(0,10,20))   #列表就是方括号里面有很多空格分开的数据,数组就是方括号中有很多方括号包含着的数据
zz = 2.4 * xx + 4.5 * yy + np.random.randint(0,100,(20,20))
#构建成特征、值的形式
X, Z = np.column_stack((xx.flatten(),yy.flatten())), zz.flatten()
print("xx.flatten() is:",xx.flatten())
#线性回归分析
regr = linear_model.LinearRegression()
regr.fit(X, Z)
#预测的一个特征
x_test = np.array([[15.7, 91.6]])
print (regr.predict(x_test))
#画图可视化分析
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(xx, yy, zz) #真实点
#拟合的平面
ax.plot_wireframe(xx, yy, regr.predict(X).reshape(20,20))
ax.plot_surface(xx, yy, regr.predict(X).reshape(20,20), alpha=0.3)
plt.show()四. Pizza数据集一元和多元线性回归分析
from sklearn.linear_model import LinearRegression#数据集 直径、价格
x = [[5],[6],[7],[8],[10],[11],[13],[14],[16],[18]]
y = [[6],[7.5],[8.6],[9],[12],[13.6],[15.8],[18.5],[19.2],[20]]clf = LinearRegression()
clf.fit(x,y)
pre = clf.predict([12])[0]
print(u'预测直径为12英寸的价格: $%.2f' % pre)
x2 = [[0],[12],[15],[25]]
y2 = clf.predict(x2)import matplotlib.pyplot as plt
import numpy as npplt.figure()
plt.axis([0,25,0,25])
plt.scatter(x,y,marker="s",s=20)
plt.plot(x2,y2,"g-")#导入多项式回归模型
from sklearn.preprocessing import PolynomialFeatures
xx = np.linspace(0,25,100) #0到25等差数列
quadratic_featurizer = PolynomialFeatures(degree = 2) #实例化一个二次多项式
x_train_quadratic = quadratic_featurizer.fit_transform(x) #用二次多项式多样本x做变换
X_test_quadratic = quadratic_featurizer.transform(x2)
regressor_quadratic = LinearRegression()
regressor_quadratic.fit(x_train_quadratic, y)
xx_quadratic = quadratic_featurizer.transform(xx.reshape(xx.shape[0], 1))# 把训练好X值的多项式特征实例应用到一系列点上,形成矩阵plt.plot(xx, regressor_quadratic.predict(xx_quadratic),label="$y = ax^2 + bx + c$",linewidth=2,color="r")
plt.legend()
plt.show()

python数据挖掘笔记】十八.线性回归及多项式回归分析四个案例分享相关推荐

  1. 【python数据挖掘课程】十八.线性回归及多项式回归分析四个案例分享

    这是<Python数据挖掘课程>系列文章,也是我这学期大数据金融学院上课的部分内容.本文主要讲述和分享线性回归作业中,学生们做得比较好的四个案例,经过我修改后供大家学习,内容包括:     ...

  2. python数据挖掘笔记】二十.KNN最近邻分类算法分析详解及平衡秤TXT数据集读取

    #2018-04-06 07:57:00 April Friday the 14 week, the 096 day SZ SSMR python数据挖掘笔记]二十.KNN最近邻分类算法分析详解及平衡 ...

  3. python3.4学习笔记(十八) pycharm 安装使用、注册码、显示行号和字体大小等常用设置...

    python3.4学习笔记(十八) pycharm 安装使用.注册码.显示行号和字体大小等常用设置 Download JetBrains Python IDE :: PyCharm http://ww ...

  4. Python数据挖掘笔记 七 .PCA降维操作及subplot子图绘制

    Python数据挖掘笔记 七 .PCA降维操作及subplot子图绘制 这篇文章主要介绍四个知识点,也是我那节课讲课的内容.1.PCA降维操作:2.Python中Sklearn的PCA扩展包:3.Ma ...

  5. windows内核开发学习笔记十八:IRP 处理的标准模式

    windows内核开发学习笔记十八:IRP 处理的标准模式 在 Windows 内核中的请求基本上是通过 I/O Request Packet 完成的. I/O manager ---> Dis ...

  6. Polyworks脚本开发学习笔记(十八)-用SDK开发Polyworks插件

    Polyworks脚本开发学习笔记(十八)-用SDK开发Polyworks插件 插件是由PolyWorks加载的动态链接库(DLL文件),然后查询Polyworks模块,以确定它们具有哪些功能,提供给 ...

  7. python图像处理笔记-十二-图像聚类

    python图像处理笔记-十二-图像聚类 学习内容 这一章主要在学习的是聚类算法以及其在图像算法中的应用,主要学习的聚类方法有: KMeans 层次聚类 谱聚类 并将使用他们对字母数据及进行聚类处理, ...

  8. STM32复习笔记(十八) —— 高级定时器(输出比较)

    STM32复习笔记(十八) -- 高级定时器(输出比较) 1.配置步骤 1)选择计数器时钟 (内部,外部,预分频器) 2)将相应的数据写入TIMx_ARR and TIMx_CCRx寄存器中 3)可设 ...

  9. 【Python数据挖掘课程】五.线性回归知识及预测糖尿病实例

    今天主要讲述的内容是关于一元线性回归的知识,Python实现,包括以下内容:         1.机器学习常用数据集介绍         2.什么是线性回顾         3.LinearRegre ...

最新文章

  1. ECCV 2018 | OR-CNN行人检测:为‘遮挡’而生
  2. OpenGL Static Texture静态纹理的实例
  3. 第三百一十九节,Django框架,文件上传
  4. MPU和CPU有什么区别?
  5. windows下的diskpart指令彻底格式化清除U盘
  6. java虚拟机规范 51cto_java虚拟机
  7. java 3_Java 3 (Java的数据类型)
  8. mac mysql 默认字符集_MacOS中Mysql设置默认字符集
  9. linux网络编程之socket:使用fork并发处理多个client的请求
  10. 【Android综合应用】概述
  11. 技术人员,你的表达能力怎样?
  12. VS提示error C2011: “timespec”:“struct”类型重定义
  13. 账号注册邮箱激活设计
  14. 【端口扫描工具】mascan核心使用
  15. redis hset hget字典的实现
  16. Learning optical flow from still images
  17. C# 开发的 webBrowser打开网页出现脚本错误解决
  18. 客户端无法向springcloud注册中心注册服务,提示连接超时
  19. 解决vs编译后运行提示“系统找不到指定的文件”的问题
  20. latex 显示黑色的点命令 black dot.

热门文章

  1. Spring之AOP代理模式
  2. golang字节数组拷贝BlockCopy函数实现
  3. STL之stack容器
  4. centos图形界面,vncserver
  5. DMA(2) S3C2410 DMA详解(其它的其实类似)
  6. Linux 命令 - curl: transfer a URL
  7. [导入]MSIL: call callvirt
  8. 安卓应用安全指南 5.2.2 权限和保护级别 规则书
  9. Web Hacking 101 中文版 十四、XML 外部实体注入(一)
  10. Web Hacking 101 中文版 五、HTML 注入