how to calculate the best fit to a plane in 3D, and how to find the corresponding statistical parameters
sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程)
https://study.163.com/course/introduction.htm?courseId=1005269003&utm_campaign=commission&utm_source=cp-400000000398149&utm_medium=share
# -*- coding: utf-8 -*-
'''
python入门/爬虫/人工智能/机器学习/自然语言/数据统计分析视频教程网址
https://pythoner.taobao.com/ https://github.com/thomas-haslwanter/statsintro_python/tree/master/ISP/Code_Quantlets/12_Multivariate/multipleRegression
Multiple Regression
- Shows how to calculate the best fit to a plane in 3D, and how to find the
corresponding statistical parameters.
- Demonstrates how to make a 3d plot.
- Example of multiscatterplot, for visualizing correlations in three- to
six-dimensional datasets.
'''
# Import standard packages
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns # additional packages
import sys
import os
sys.path.append(os.path.join('..', '..', 'Utilities')) try:
# Import formatting commands if directory "Utilities" is available
from ISP_mystyle import showData except ImportError:
# Ensure correct performance otherwise
def showData(*options):
plt.show()
return # additional packages ...
# ... for the 3d plot ...
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm # ... and for the statistic
from statsmodels.formula.api import ols def generateData():
''' Generate and show the data: a plane in 3D '''
#随机产生101个数据,取值范围从(-5到5)
x = np.linspace(-5,5,101)
(X,Y) = np.meshgrid(x,x)
# To get reproducable values, I provide a seed value
np.random.seed(987654321)
#np.random.randn产生随机的正太分布数,np.shape(X)表示X的size(101,101)
#np.random.randn(np.shape(X)[0], np.shape(X)[1])表示产生(101,101)个随机数
Z = -5 + 3*X-0.5*Y+np.random.randn(np.shape(X)[0], np.shape(X)[1]) # 绘图
#Set the color
myCmap = cm.GnBu_r
# If you want a colormap from seaborn use:
#from matplotlib.colors import ListedColormap
#myCmap = ListedColormap(sns.color_palette("Blues", 20)) # Plot the figure
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X,Y,Z, cmap=myCmap, rstride=2, cstride=2,
linewidth=0, antialiased=False)
ax.view_init(20,-120)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
fig.colorbar(surf, shrink=0.6) outFile = '3dSurface.png'
showData(outFile)
#X.flatten()把多维数据展开,弄成一维数据
return (X.flatten(),Y.flatten(),Z.flatten()) def regressionModel(X,Y,Z):
'''Multilinear regression model, calculating fit, P-values, confidence intervals etc.''' # Convert the data into a Pandas DataFrame
df = pd.DataFrame({'x':X, 'y':Y, 'z':Z}) # --- >>> START stats <<< ---
# Fit the model
model = ols("z ~ x + y", df).fit()
# Print the summary
print((model.summary()))
# --- >>> STOP stats <<< ---
return model._results.params # should be array([-4.99754526, 3.00250049, -0.50514907]) #用numpy的线性回归模型,和上面regressionModel函数计算结果一致
def linearModel(X,Y,Z):
'''Just fit the plane, using the tools from numpy''' # --- >>> START stats <<< ---
M = np.vstack((np.ones(len(X)), X, Y)).T
bestfit = np.linalg.lstsq(M,Z)
# --- >>> STOP stats <<< ---
print(('Best fit plane:', bestfit))
return bestfit if __name__ == '__main__':
(X,Y,Z) = generateData()
regressionModel(X,Y,Z)
linearModel(X,Y,Z)
python风控评分卡建模和风控常识(博客主亲自录制视频教程)
how to calculate the best fit to a plane in 3D, and how to find the corresponding statistical parameters的更多相关文章
- (转)Markov Chain Monte Carlo
Nice R Code Punning code better since 2013 RSS Blog Archives Guides Modules About Markov Chain Monte ...
- What is an eigenvector of a covariance matrix?
What is an eigenvector of a covariance matrix? One of the most intuitive explanations of eigenvector ...
- kaggle入门项目:Titanic存亡预测(四)模型拟合
原kaggle比赛地址:https://www.kaggle.com/c/titanic 原kernel地址:A Data Science Framework: To Achieve 99% Accu ...
- Course Machine Learning Note
Machine Learning Note Introduction Introduction What is Machine Learning? Two definitions of Machine ...
- [C2P3] Andrew Ng - Machine Learning
##Advice for Applying Machine Learning Applying machine learning in practice is not always straightf ...
- AI-IBM-cognitive class --Liner Regression
Liner Regression import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy ...
- OpenCASCADE PCurve of Topological Face
OpenCASCADE PCurve of Topological Face eryar@163.com Abstract. OpenCASCADE provides a class BRepBuil ...
- The Model Complexity Myth
The Model Complexity Myth (or, Yes You Can Fit Models With More Parameters Than Data Points) An oft- ...
- 中国澳门sinox很多平台CAD制图、PCB电路板、IC我知道了、HDL硬件描述语言叙述、电路仿真和设计软件,元素分析表
中国澳门sinox很多平台CAD制图.PCB电路板.IC我知道了.HDL硬件描述语言叙述.电路仿真和设计软件,元素分析表,可打开眼世界. 最近的研究sinox执行windows版protel,powe ...
随机推荐
- QT 子窗口退出全屏
m_pWidget代表子窗口, 子窗口显示全屏: m_pWidget->setWindowFlags(Qt::Dialog); m_pWidget->showFullScreen(); 子 ...
- 20150401 作业2 结对 四则运算ver 1.0
Web項目下 Tomcat服務器的路徑 /WebContant/ 目錄下 SE2_2.jsp <%@ page language="java" contentType=&qu ...
- B01-java学习-阶段2-面向对象
对象内存分析 构造方法 类的深入解释 预定义类型和自定义类型深入分析和解释 预定义类源码的查看 预定义类和自定义类的对比 跨过类中使用自定义类型作为属性类型的门槛 构造方法的定义和执行过程 编译器提供 ...
- ASP.NET MVC自定义异常处理
1.自定义异常处理过滤器类文件 新建MyExceptionAttribute.cs异常处理类文件
- Xshell 使用数字小键盘进行vim 写入操作.
Copy From http://blog.csdn.net/shenzhen206/article/details/51200869 感谢原作者 在putty或xshell上用vi/vim的时候,开 ...
- webpack4.x相关笔记整理
概念 Webpack是一个模块打包机,它可以将我们项目中的所有js.图片.css等资源,根据其入口文件的依赖关系,打包成一个能被浏览器识别的js文件.能够帮助前端开发将打包的过程更智能化和自动化. W ...
- js私有作用域(function(){})(); 模仿块级作用域
摘自:http://outofmemory.cn/wr/?u=http%3A%2F%2Fwww.phpvar.com%2Farchives%2F3033.html js没有块级作用域,简单的例子: f ...
- pandas聚合aggregate
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/5/24 15:03 # @Author : zhang chao # @Fi ...
- pandas合并/连接
Pandas具有功能全面的高性能内存中连接操作,与SQL等关系数据库非常相似.Pandas提供了一个单独的merge()函数,作为DataFrame对象之间所有标准数据库连接操作的入口 - pd.me ...
- pip和conda到底有什么不一样?
今天看到我的foreman开始报错去询问才发现.我们的python包管理工具已经从pip整体迁移到了conda..最近的迁移真的非常多..前端也在迁移打包