LogisticRegression in MLLib (PySpark + numpy+matplotlib可视化)
参考'LogisticRegression in MLLib' (http://www.cnblogs.com/luweiseu/p/7809521.html)
通过pySpark MLlib训练logistic模型,再利用Matplotlib作图画出分类边界。
from pyspark.sql import Row
from pyspark.sql import HiveContext
import pyspark
from IPython.display import display
import matplotlib
import matplotlib.pyplot as plt
import os
os.environ['SPARK_HOME'] ="C:\\Users\\software\\spark-2.1.0-bin-hadoop2.7"
%matplotlib inline
sc = pyspark.SparkContext(master='local').getOrCreate()
sqlContext = HiveContext(sc)
# get data
irisData = sc.textFile("iris.txt")
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.linalg import Vectors
from pyspark.mllib.classification import LogisticRegressionWithLBFGS
def toLabeledPoint(line):
linesp = line.split()
return LabeledPoint(int(linesp[2]), Vectors.dense(float(linesp[0]), float(linesp[1])))
data = irisData.map(toLabeledPoint)
#Split data into training (60%) and test (40%).
splits = data.randomSplit([0.6, 0.4],seed=11)
training = splits[0].cache()
test = splits[1]
trainer = LogisticRegressionWithLBFGS()
model = trainer.train(training,intercept=True,numClasses=3)
# testdata
def predicTest(lp):
label=lp.label
features=lp.features
prediction = model.predict(features)
return (float(prediction), label)
predictionAndLabels = test.map(predicTest)
from pyspark.mllib.evaluation import MulticlassMetrics
#accuracy
metrics = MulticlassMetrics(predictionAndLabels)
accuracy = metrics.accuracy
accuracy
# plot boundary
import numpy as np
## meshgrid
x0, x1 = np.meshgrid(
np.linspace(0, 8, 500).reshape(-1, 1),
np.linspace(0, 3.5, 200).reshape(-1, 1),
)
X_new = np.c_[x0.ravel(), x1.ravel()]
## predict
y_predict = [model.predict(Vectors.dense(X_new_i)) for X_new_i in X_new]
y = data.map(lambda d: d.label).collect()
X = data.map(lambda d: [d.features[0], d.features[1]]).collect()
y=np.array(y)
X=np.array(X)
## draw
zz = np.array(y_predict).reshape(x0.shape)
plt.figure(figsize=(10, 4))
plt.plot(X[y==2, 0], X[y==2, 1], "g^", label="Iris-Virginica")
plt.plot(X[y==1, 0], X[y==1, 1], "bs", label="Iris-Versicolor")
plt.plot(X[y==0, 0], X[y==0, 1], "yo", label="Iris-Setosa")
from matplotlib.colors import ListedColormap
custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
plt.contourf(x0, x1, zz, cmap=custom_cmap, linewidth=5)
# plt.clabel(contour, inline=1, fontsize=12)
plt.xlabel("Petal length", fontsize=14)
plt.ylabel("Petal width", fontsize=14)
plt.legend(loc="center left", fontsize=14)
plt.axis([0, 7, 0, 3.5])
plt.show()
最终结果:

LogisticRegression in MLLib (PySpark + numpy+matplotlib可视化)的更多相关文章
- 2-4 Numpy+Matplotlib可视化(二)
自定义绘图 # -*-coding:utf-8-*- # !/usr/bin/env python # Author:@vilicute import numpy as np import matpl ...
- 2-3 Numpy+Matplotlib可视化(一)
(1)pyplot基础绘图 # -*-coding:utf-8-*- # !/usr/bin/env python # Author:@vilicute import numpy as np impo ...
- 【学习总结】GirlsInAI ML-diary day-21-初识 Numpy, Matplotlib, Seanborn [柱状图、折线图、箱图]
[学习总结]GirlsInAI ML-diary 总 原博github链接-day21 初识 Numpy, Matplotlib, Seanborn [柱状图.折线图.箱图] 一.Titanic练习赛 ...
- 国外大神制作的一个很棒的matplotlib 可视化教程
国外大神制作的一个很棒的matplotlib 可视化教程 参考:https://www.machinelearningplus.com/plots/top-50-matplotlib-visualiz ...
- 在mac安装numpy matplotlib scipy
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #000000; background-color: #fffff ...
- Ubuntu-Python2.7安装 scipy,numpy,matplotlib 和pip
一. scipy,numpy,matplotlib sudo apt-get install python-scipy sudo apt-get install python-numpy sudo a ...
- NumPy Matplotlib库
NumPy - Matplotlib Matplotlib 是 Python 的绘图库. 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案. 它也可以和图形工具包一起使用,如 ...
- 21、numpy—Matplotlib
NumPy Matplotlib Matplotlib 是 Python 的绘图库. 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案. 它也可以和图形工具包一起使用,如 P ...
- SciKit-Learn 使用matplotlib可视化数据
章节 SciKit-Learn 加载数据集 SciKit-Learn 数据集基本信息 SciKit-Learn 使用matplotlib可视化数据 SciKit-Learn 可视化数据:主成分分析(P ...
随机推荐
- Partition Array Into Three Parts With Equal Sum LT1013
Given an array A of integers, return true if and only if we can partition the array into three non-e ...
- Android NDK定位.so文件crash代码位置
参考:http://blog.csdn.net/xyang81/article/details/42319789 问题: QRD8926_110202平台的Browser必现报错.(去年的项 ...
- stm8 单线串口能收不能发
原因是把连接的TX和RX短接了,其实在TX和RX间要串一个电阻,然后让stm8的单线TX接到RX.
- spring自动类型转换========Converter和PropertyEditor
Spring有两种自动类型转换器,一种是Converter,一种是propertyEditor. 两者的区别:Converter是类型转换成类型,Editor:从string类型转换为其他类型. 从某 ...
- 数学小知识点整理(TBC)
文章目录 前言 素数与同余 线性筛部分 素数 线性递推逆元 指数循环节降幂 当求逆元时模数与求逆元的数有可能不互质时的处理方法 一个神奇的结论 拓展欧拉定理 杂乱的一些性质/技巧 二进制枚举子集 异或 ...
- 2018.11.09 codeforces487E. Tourists(tarjan+树链剖分)
传送门 先把边双连通分量用圆方树一样的方法缩点,然后把新建的树树剖维护. 注意对于边双连通分量需要维护动态最小值,可以用multisetmultisetmultiset. 代码: #include&l ...
- Java,数据库中的数据导入到Excel
private static void executeMethod(JobExecutionContext arg0) throws Exception{ try { TContrastService ...
- idea的maven项目不知道为啥下载不下来jar包,看本地仓库只是下载了一下xml文件,没有jar包问题
确认了私服上的jar包能直接下载下来,而且jar包是正常的:但是就是不能通过idea下载,通过idea下载到本地仓库的只生成了.lastUpdated文件,检查了setting.xml文件.网络,私服 ...
- IntelliJ IDEA 2017版 编译器使用学习笔记(八) (图文详尽版);IDE快捷键使用;IDE代码重构(寻找修改痕迹)
git集成: 快速找到版本控制器中某段代码的作者 一.annotate 选中某行代码,右键,选择annotate,鼠标放于其上就会显示注释 二.移动所有改动之处: prev ...
- fPLL结构及动态配置
输入参考时钟 从上图可以看到参考时钟输入的几种类型. 注意:fPLL的校正是由CLKUSR来驱动的,这个时钟必须要保持稳定. 参考时钟利用器 N计数器 N计数器会把参考时钟利用器输出进行分 ...