跟着chatgpt一起学|1.spark入门之MLLib

news2025/2/22 18:38:50

chatgpt在这一章表现的不好,所以我主要用它来帮我翻译文章+提炼信息

1.前言

首先找到spark官网里关于MLLib的链接

spark内一共有2种支持机器学习的包,

一种是spark.ml,基于DataFrame的,也是目前主流的

另一种则是spark.mllib,是基于RDD的,在维护,但不增加新特性了

所以这一节的学习以spark.ml中的pipeline为主。其他的和sklearn里的非常像,大家可以自己去看。

2.Pipeline介绍

基于DataFrame创建pipeline,对数据进行清洗/转换/训练。

2.1 Pipeline的构成

Pipeline主要分为:

1.Transformer,人如其名,就是对数据做转换的

2.Estimators,使用fit函数对数据做拟合,

2.2 Pipeline如何工作

pipeline是由一系列stage构成,而每一个stage则是由一个transformer或者是estimator构成。这些stage按顺序执行,将输入的DataFrame按相应的方式转换:Transformer对应的stage调用transform()函数,而Estimator对应的stage则调用fit函数取创建一个Transformer,(它成为PipelineModel或已拟合的Pipeline的一部分),然后在DataFrame上调用该Transformer的transform()方法。

有些绕,可以看看下面这张图:

对训练数据进行pipeline操作,对应的红框表示Estimator,使用训练数据拟合LR

而对测试数据,对应的LR变成了蓝框,此时LR也成为了Transformer,对测试数据进行transform()操作。

3.注意项

1.执行DAG图

上面展示的顺序执行pipeline的方式,实际上满足无环拓扑图也可以使用pipeline

2.参数

  • 可以直接设置 lr.setMaxIter(10) 
  • 在调用transform()或者fit时传入ParamMap

3.兼容性

不同版本的MLlib兼容性其实并不完全能保证的

主要版本:不能保证,但会尽力兼容。

小版本和补丁版本:是的,它们是向后兼容的。

4.代码参考:

4.1 Estimator, Transformer, and Param代码参考

from pyspark.ml.linalg import Vectors
from pyspark.ml.classification import LogisticRegression

# Prepare training data from a list of (label, features) tuples.
training = spark.createDataFrame([
    (1.0, Vectors.dense([0.0, 1.1, 0.1])),
    (0.0, Vectors.dense([2.0, 1.0, -1.0])),
    (0.0, Vectors.dense([2.0, 1.3, 1.0])),
    (1.0, Vectors.dense([0.0, 1.2, -0.5]))], ["label", "features"])

# Create a LogisticRegression instance. This instance is an Estimator.
lr = LogisticRegression(maxIter=10, regParam=0.01)
# Print out the parameters, documentation, and any default values.
print("LogisticRegression parameters:\n" + lr.explainParams() + "\n")

# Learn a LogisticRegression model. This uses the parameters stored in lr.
model1 = lr.fit(training)

# Since model1 is a Model (i.e., a transformer produced by an Estimator),
# we can view the parameters it used during fit().
# This prints the parameter (name: value) pairs, where names are unique IDs for this
# LogisticRegression instance.
print("Model 1 was fit using parameters: ")
print(model1.extractParamMap())

# We may alternatively specify parameters using a Python dictionary as a paramMap
paramMap = {lr.maxIter: 20}
paramMap[lr.maxIter] = 30  # Specify 1 Param, overwriting the original maxIter.
# Specify multiple Params.
paramMap.update({lr.regParam: 0.1, lr.threshold: 0.55})  # type: ignore

# You can combine paramMaps, which are python dictionaries.
# Change output column name
paramMap2 = {lr.probabilityCol: "myProbability"}
paramMapCombined = paramMap.copy()
paramMapCombined.update(paramMap2)  # type: ignore

# Now learn a new model using the paramMapCombined parameters.
# paramMapCombined overrides all parameters set earlier via lr.set* methods.
model2 = lr.fit(training, paramMapCombined)
print("Model 2 was fit using parameters: ")
print(model2.extractParamMap())

# Prepare test data
test = spark.createDataFrame([
    (1.0, Vectors.dense([-1.0, 1.5, 1.3])),
    (0.0, Vectors.dense([3.0, 2.0, -0.1])),
    (1.0, Vectors.dense([0.0, 2.2, -1.5]))], ["label", "features"])

# Make predictions on test data using the Transformer.transform() method.
# LogisticRegression.transform will only use the 'features' column.
# Note that model2.transform() outputs a "myProbability" column instead of the usual
# 'probability' column since we renamed the lr.probabilityCol parameter previously.
prediction = model2.transform(test)
result = prediction.select("features", "label", "myProbability", "prediction") \
    .collect()

for row in result:
    print("features=%s, label=%s -> prob=%s, prediction=%s"
          % (row.features, row.label, row.myProbability, row.prediction))

4.2 Pipeline 代码参考

from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.feature import HashingTF, Tokenizer

# Prepare training documents from a list of (id, text, label) tuples.
training = spark.createDataFrame([
    (0, "a b c d e spark", 1.0),
    (1, "b d", 0.0),
    (2, "spark f g h", 1.0),
    (3, "hadoop mapreduce", 0.0)
], ["id", "text", "label"])

# Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.
tokenizer = Tokenizer(inputCol="text", outputCol="words")
hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features")
lr = LogisticRegression(maxIter=10, regParam=0.001)
pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])

# Fit the pipeline to training documents.
model = pipeline.fit(training)

# Prepare test documents, which are unlabeled (id, text) tuples.
test = spark.createDataFrame([
    (4, "spark i j k"),
    (5, "l m n"),
    (6, "spark hadoop spark"),
    (7, "apache hadoop")
], ["id", "text"])

# Make predictions on test documents and print columns of interest.
prediction = model.transform(test)
selected = prediction.select("id", "text", "probability", "prediction")
for row in selected.collect():
    rid, text, prob, prediction = row
    print(
        "(%d, %s) --> prob=%s, prediction=%f" % (
            rid, text, str(prob), prediction   # type: ignore
        )
    )

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1255695.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MATLAB 和 Simulink 官方文档下载地址

MATLAB 官方文档中文版下载网址: https://ww2.mathworks.cn/help/pdf_doc/matlab/index.html 如图: MATLAB 官方文档英文版下载网址: https://ww2.mathworks.cn/help/pdf_doc/matlab/index.html?langen 如图: Simulink 官…

02、Tensorflow实现手写数字识别(数字0-9)

02、Tensorflow实现手写数字识别(数字0-9) 开始学习机器学习啦,已经把吴恩达的课全部刷完了,现在开始熟悉一下复现代码。对这个手写数字实部比较感兴趣,作为入门的素材非常合适。 基于Tensorflow 2.10.0与pycharm 1…

WebSocket协议测试实战

当涉及到WebSocket协议测试时,有几个关键方面需要考虑。在本文中,我们将探讨如何使用Python编写WebSocket测试,并使用一些常见的工具和库来简化测试过程。 1、什么是WebSocket协议? WebSocket是一种在客户端和服务器之间提供双向…

基于OPC UA 的运动控制读书笔记(1)

最近一段时间集中研究OPCUA 在机器人控制应用中应用的可能性。这个话题自然离不开运动控制。 笔者对运动控制不是十分了解。于是恶补EtherCAT 驱动,PLCopen 运动控制的知识,下面是自己的读书笔记和实现OPCUA /IEC61499 运动控制器的实现方案设想。 PLCo…

【Spring整合Junit】Spring整合Junit介绍

本文内容基于【Spring整合MyBatis】Spring整合MyBatis的具体方法进行测试 文章目录 1. 导入相关坐标2. 使用Junit测试所需注解3. 在测试类中写相关内容 1. 导入相关坐标 在pom.xml中导入相关坐标&#xff1a; <dependency><groupId>junit</groupId><ar…

CSS常用笔记

1. 脱离文档流&#xff0c;用于微调 {position: relative; top: 10px; right: 0; } 2. flex布局大法 <div class"demo"><div class"demo-1"></div><div class"demo-2"></div><div class"demo-3"&…

Linux面试题(二)

目录 17、怎么使一个命令在后台运行? 18、利用 ps 怎么显示所有的进程? 怎么利用 ps 查看指定进程的信息&#xff1f; 19、哪个命令专门用来查看后台任务? 20、把后台任务调到前台执行使用什么命令?把停下的后台任务在后台执行起来用什么命令? 21、终止进程用什么命令…

【计网 面向连接的传输TCP】 中科大笔记 (十 二)

目录 0 引言1 TCP 的特性1.1 拓展&#xff1a;全双工、单工、半双工通信 2 TCP报文段结构3 TCP如何实现RDT4 TCP 流量控制4.1 题外话&#xff1a;算法感悟 5 TCP连接3次握手、断开连接4次握手5.1 连接5.2 断开连接 6 拥塞控制6.1 拥塞控制原理6.2 TCP拥塞控制 &#x1f64b;‍♂…

shell脚本 ( 函数 数组 冒泡排序)

目录 什么是函数 使用函数的方法 格式 注意事项 函数的使用 函数可以直接使用 函数变量的作用范围 函数返回值 查看函数 删除函数 函数的传递参数 使用函数文件 ​编辑 拓展递归函数 例&#xff1a;求5的阶乘 什么是数组 使用数组的方法 1.先声明 2.定义数组 3…

Python---函数的数据---拆包的应用案例(两个变量值互换,*args, **kwargs调用时传递参数用法)

案例&#xff1a; 使用至少3种方式交换两个变量的值 第一种方式&#xff1a;引入一个临时变量 c1 10 c2 2# 引入临时变量temp temp c2 c2 c1 c1 tempprint(c1, c2) 第二种方式&#xff1a;使用加法与减法运算交换两个变量的值&#xff08;不需要引入临时变量&#xff09…

ArcGIS制作广场游客聚集状态及密度图

文章目录 一、加载实验数据二、平均最近邻法介绍1. 平均最近邻工具2. 广场游客聚集状态3. 结果分析三、游客密度制图一、加载实验数据 二、平均最近邻法介绍 1. 平均最近邻工具 “平均最近邻”工具将返回五个值:“平均观测距离”、“预期平均距离”、“最近邻指数”、z 得分和…

C++学习之路(五)C++ 实现简单的文件管理系统命令行应用 - 示例代码拆分讲解

简单的文件管理系统示例介绍: 这个文件管理系统示例是一个简单的命令行程序&#xff0c;允许用户进行文件的创建、读取、追加内容和删除操作。这个示例涉及了一些基本的文件操作和用户交互。 功能概述&#xff1a; 创建文件 (createFile())&#xff1a; 用户可以输入文件名和内…

计算机系统的层次结构与性能指标

目录 一. 计算机系统的层次结构二. 计算机性能指标2.1. 存储器的性能指标2.2 CPU的性能指标2.3 系统整体的性能指标2.4 系统整体的性能指标(动态测试) \quad 一. 计算机系统的层次结构 \quad \quad 虚拟机器的意思是看起来像是机器直接就能执行程序员所写的代码, 其实是需要通过…

Java王者荣耀

一、创建项目 二、代码 package com.sxt;import javax.swing.*; import java.awt.*;public class Background extends GameObject {public Background(GameFrame gameFrame) {super(gameFrame);// TODO Auto-generated constructor stub}Image bg Toolkit.getDefaultToolkit(…

基于helm的方式在k8s集群中部署gitlab - 备份恢复(二)

接上一篇 基于helm的方式在k8s集群中部署gitlab - 部署&#xff08;一&#xff09;&#xff0c;本篇重点介绍在k8s集群中备份gitlab的数据&#xff0c;并在虚拟机上部署相同版本的gitlab&#xff0c;然后将备份的数据进行还原恢复 文章目录 1. 备份2. 恢复到虚拟机上的gitlab2.…

java学习part13Object类和常用方法

1.Object 2.常用方法 2.1clone() clone()就是深拷贝&#xff0c;创建一个同内容新对象。需要实现接口 2.2finalize()已废弃 类似于析构函数&#xff0c;在GC回收之前调用。 System.gc()强制调用gc&#xff0c;然后就能看到finalize()的输出 2.3equals() 对于引用类型可用。…

帮管客CRM SQL注入漏洞复现

0x01 产品简介 帮管客CRM是一款集客户档案、销售记录、业务往来等功能于一体的客户管理系统。帮管客CRM客户管理系统&#xff0c;客户管理&#xff0c;从未如此简单&#xff0c;一个平台满足企业全方位的销售跟进、智能化服务管理、高效的沟通协同、图表化数据分析帮管客颠覆传…

Linux(8):BASH

硬件、核心与 Shell 操作系统其实是一组软件&#xff0c;由于这组软件在控制整个硬件与管理系统的活动监测&#xff0c;如果这组软件能被用户随意的操作&#xff0c;若使用者应用不当&#xff0c;将会使得整个系统崩溃。因为操作系统管理的就是整个硬件功能。 应用程序在最外层…

ELF分析(以CS:APP linkLab的文件为例)

文件结构&#xff1a;gcc -o test main.o phase1.o 可执行文件的段头表&#xff08;又称程序头表&#xff09;&#xff08;用于描述本文件到虚拟内存的映射&#xff09; text文件的段头表如下。 上图有两个LOAD。它们的区别是权限不同。LOAD1是可读可执行&#xff08;这里面存…

拍这个视频把脸都扇肿了,midjourney官网效果复现

我是如何复现midjourney官网首页效果的&#xff1f; 视频讲解地址&#xff1a;[https://www.bilibili.com/video/BV1FQ4y1p7HC/](https://www.bilibili.com/video/BV1FQ4y1p7HC/)原理&#xff0c;过程&#xff0c;代码讲解 大家好&#xff0c;这一集我来讲一下 字符花园里 总结…