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 ...
随机推荐
- Linux内核分析——进程的描述和进程的创建
进程的描述和进程的创建 一. 进程的描述 (一)进程控制块PCB——task_struct 1.操作系统的三大管理功能包括: (1)进程管理 (2)内存管理 (3)文件系统 2.PCB task_st ...
- SRS用例
团队项目:超市管理系统 作者:王琨 个人博客地址:http://www.cnblogs.com/wangkun123 一. 用例视图概述 一般的超市商品管理系统,主要由五大模块组成,即商品信 ...
- PHP预防跨站脚本(XSS)攻击且不影响html代码显示效果
什么是XSS 跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS.恶意攻击者往 ...
- Jmeter While Controller 使用${__jexl2(,)}
1. String [] str ={"1","2","3"}; vars.putObject("strArray",s ...
- 面象对象设计原则之二:开放封闭原则(Open-Closed Principle, OCP)
开闭原则是面向对象的可复用设计的第一块基石,它是最重要的面向对象设计原则.开闭原则由Bertrand Meyer于1988年提出,其定义如下: 开闭原则(Open-Closed Principle, ...
- 记Git报错-refusing to merge unrelated histories
记Git报错-refusing to merge unrelated histories 系统:win7 git版本: 2.16.2.windows.1 问题 1.本地初始化了git仓库,放了一些 ...
- C++的内存分区
C++的内存划分为栈区.堆区.全局区/静态区.字符串常量和代码区. 栈区 由系统进行内存的管理. 主要存放函数的参数以及局部变量.在函数完成执行,系统自行释放栈区内存,不需要用户管理.整个程序的栈区的 ...
- React 支持JS
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...
- OneZero产品视频
产品视频地址:http://v.youku.com/v_show/id_XMTU1MDMwOTk2OA==.html
- Linux基础学习(3)--初学注意
第三章——初学注意 一.学习Linux的注意事项 1.Linux严格区分大小写 2.Linux中所有内容以文件形式保存,包括硬件: (1)硬盘文件是/dev/sd[a-p] (2)光盘文件是/dev/ ...