900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > python数据挖掘笔记】十八.线性回归及多项式回归分析四个案例分享

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

时间:2023-09-23 10:03:47

相关推荐

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

python数据挖掘课程】十八.线性回归及多项式回归分析四个案例分享 #-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 pltplt.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 -*-#导入数据集bostonfrom sklearn.datasets import load_bostonimport 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 -*-#导入数据集bostonfrom sklearn.datasets import load_bostonimport 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 pltplt.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 npimport mathX = 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 pltplt.plot(xArr, yArr, 'go')plt.show()接下来需要调用Sklearn机器学习扩展包相关函数进行线性回归分析。2.线性回归完整代码如下:import numpy as npimport mathX = 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 pltplt.plot(xArr, yArr, '*')plt.show()'''#线性回归分析from sklearn.linear_model import LinearRegressionclf = 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 pltplt.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 npfrom sklearn import linear_modelfrom mpl_toolkits.mplot3d import Axes3D #3D画图模块import matplotlib.pyplot as pltimport 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 pltimport 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 PolynomialFeaturesxx = 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()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。