Spark机器学习1·编程入门(scala/java/python)
Spark安装目录
/Users/erichan/Garden/spark-1.4.0-bin-hadoop2.6
- 基本测试
./bin/run-example org.apache.spark.examples.SparkPi
MASTER=local[20] ./bin/run-example org.apache.spark.examples.SparkPi
scala
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
/**
* A simple Spark app in Scala
*/
object ScalaApp {
def main(args: Array[String]) {
val sc = new SparkContext("local[2]", "First Spark App")
val data = sc.textFile("data/UserPurchaseHistory.csv")
.map(line => line.split(","))
.map(purchaseRecord => (purchaseRecord(0), purchaseRecord(1), purchaseRecord(2)))
val numPurchases = data.count()
val uniqueUsers = data.map { case (user, product, price) => user }.distinct().count()
val totalRevenue = data.map { case (user, product, price) => price.toDouble }.sum()
val productsByPopularity = data
.map { case (user, product, price) => (product, 1) }
.reduceByKey(_ + _)
.collect()
.sortBy(-_._2)
val mostPopular = productsByPopularity(0)
println("Total purchases: " + numPurchases)
println("Unique users: " + uniqueUsers)
println("Total revenue: " + totalRevenue)
println("Most popular product: %s with %d purchases".format(mostPopular._1, mostPopular._2))
sc.stop()
}
}
build.sbt
name := "scala-spark-app"
version := "1.0"
scalaVersion := "2.11.6"
libraryDependencies += "org.apache.spark" %% "spark-core" % "1.4.0"
erichan:scala-spark-app/ $ sbt run
java 8
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;
import java.util.List;
public class JavaApp {
public static void main(String[] args) {
JavaSparkContext sc = new JavaSparkContext("local[2]", "First Spark App");
JavaRDD<String[]> data = sc.textFile("data/UserPurchaseHistory.csv").map(s -> s.split(","));
long numPurchases = data.count();
long uniqueUsers = data.map(strings -> strings[0]).distinct().count();
double totalRevenue = data.mapToDouble(strings -> Double.parseDouble(strings[2])).sum();
List<Tuple2<String, Integer>> pairs = data.mapToPair(
new PairFunction<String[], String, Integer>() {
@Override
public Tuple2<String, Integer> call(String[] strings) throws Exception {
return new Tuple2(strings[1], 1);
}
}
).reduceByKey((i1, i2) -> i1 + i2).collect();
pairs.sort((o1, o2) -> -(o1._2() - o2._2()));
String mostPopular = pairs.get(0)._1();
int purchases = pairs.get(0)._2();
System.out.println("Total purchases: " + numPurchases);
System.out.println("Unique users: " + uniqueUsers);
System.out.println("Total revenue: " + totalRevenue);
System.out.println(String.format("Most popular product: %s with %d purchases", mostPopular, purchases));
sc.stop();
}
}
Maven pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>java-spark-app</groupId>
<artifactId>java-spark-app</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
python
from pyspark import SparkContext
sc = SparkContext("local[2]", "First Spark App")
data = sc.textFile("data/UserPurchaseHistory.csv").map(lambda line: line.split(",")).map(lambda record: (record[0], record[1], record[2]))
numPurchases = data.count()
uniqueUsers = data.map(lambda record: record[0]).distinct().count()
totalRevenue = data.map(lambda record: float(record[2])).sum()
products = data.map(lambda record: (record[1], 1.0)).reduceByKey(lambda a, b: a + b).collect()
mostPopular = sorted(products, key=lambda x: x[1], reverse=True)[0]
print "Total purchases: %d" % numPurchases
print "Unique users: %d" % uniqueUsers
print "Total revenue: %2.2f" % totalRevenue
print "Most popular product: %s with %d purchases" % (mostPopular[0], mostPopular[1])
sc.stop()
cd /Users/erichan/Garden/spark-1.4.0-bin-hadoop2.6/bin
./spark-submit pythonapp.py
Spark机器学习1·编程入门(scala/java/python)的更多相关文章
- 梯度迭代树(GBDT)算法原理及Spark MLlib调用实例(Scala/Java/python)
梯度迭代树(GBDT)算法原理及Spark MLlib调用实例(Scala/Java/python) http://blog.csdn.net/liulingyuan6/article/details ...
- 三种文本特征提取(TF-IDF/Word2Vec/CountVectorizer)及Spark MLlib调用实例(Scala/Java/python)
https://blog.csdn.net/liulingyuan6/article/details/53390949
- Spark机器学习MLlib系列1(for python)--数据类型,向量,分布式矩阵,API
Spark机器学习MLlib系列1(for python)--数据类型,向量,分布式矩阵,API 关键词:Local vector,Labeled point,Local matrix,Distrib ...
- Spark机器学习7·降维模型(scala&python)
PCA(主成分分析法,Principal Components Analysis) SVD(奇异值分解法,Singular Value Decomposition) http://vis-www.cs ...
- 3000字编程入门--附带Java学习路线及视频
Title: 编程入门 GitHub: BenCoper Reference: 尚硅谷-2019 Study: 文字版+视频+实战(第一个自学的网站) Explain: 文末附带Java学习视频以及项 ...
- 问题 1014: [编程入门]阶乘求和python):(本地测试正确;但提交不对!!??)求教
问题 1014: [编程入门]阶乘求和 时间限制: 1Sec 内存限制: 128MB 提交: 27629 解决: 5450 题目描述 求Sn=1!+2!+3!+4!+5!+…+n!之值,其中n是一个数 ...
- spark Using MLLib in Scala/Java/Python
Using MLLib in ScalaFollowing code snippets can be executed in spark-shell. Binary ClassificationThe ...
- 朴素贝叶斯算法原理及Spark MLlib实例(Scala/Java/Python)
朴素贝叶斯 算法介绍: 朴素贝叶斯法是基于贝叶斯定理与特征条件独立假设的分类方法. 朴素贝叶斯的思想基础是这样的:对于给出的待分类项,求解在此项出现的条件下各个类别出现的概率,在没有其它可用信息下,我 ...
- 编程入门视频【 Python、PHP、ThinkPHP、Laravel、Mysql、微信小程序】
免费分享 Python.PHP.ThinkPHP.Laravel.Mysql.微信小程序等学习视频 点击进入搜刮 免费分享 Python.PHP.ThinkPHP.Laravel.Mysql.微信小程 ...
随机推荐
- 网络协议之p2p---一个简单的nat 穿透demo
http://www.pudn.com/downloads64/sourcecode/p2p/detail228131.html http://www.pudn.com/downloads15/sou ...
- [转]移动互联网应用技术架构简介-Restful服务
Restful是基于网络的软件系统架构风格.其优先考虑分布性和扩展性,而不是安全.错误处理.对象映射. 所以Restful架构特别适用的场合为用户快速增长的互联网和移动互联网领域,看起来很容易理解,以 ...
- Ubuntu14.4下安装FTP
今天学习了Ubuntu上安装ftp的实例. 1.window上已经安装wamp(windows + apache + mysql + php) 2.window上已安装VMware Workstati ...
- jquery获取对象的方法足以应付常见的各种类型的对象
简单对象获取 $("element:first") 获取页面上某个元素的第一个如$("div:frist")表示第一个div $("element:l ...
- 搭建一个SSM框架
刚好学完springMVC,mybatis简单的组合,总结一下 1.创建一个maven项目,引入jar包 一共这么多,除了oracle jar包是我手动添加到lib里,其他都是通过pom.xml引入的 ...
- Linux严格区分大小写
虚拟机上安装了MySQL,使用rpm -qa | grep mysql查询时却未找到安装的mysql,后面才发现Linux严格区分大小写,正确的查询命令应该为rpm -qa | grep MySQL, ...
- golang build 编译规则
文章来源: http://blog.csdn.net/varding/article/details/12675971 讲述了golang中的条件编译,摘要如下: 第一种条件编译的方法:编译标签 编译 ...
- BF算法 + KMP算法
准备: 字符串比大小:比的就是字符串里每个字符的ASCII码的大小.(其实这样的比较没有多大的意义,我们关心的是字符串是否相等,即匹配等) 字符串的存储结构:同线性表(顺序存储+链式存储) 顺序存储结 ...
- 洛谷oj U3936(分成回文串) 邀请码:a0c9
题目链接:传送门 题目大意:略 题目思路:DP 先预处理,分别以每个字母为中心处理能形成的回文串,再以两个字母为中心处理能形成的回文串. 然后 dp[i] 表示1~i 能形成的数目最少的回文串. 转移 ...
- XMLHttpRequest 对象 status 和statusText 属性对照表
XMLHttpRequest 对象 status 和statusText 属性对照表 status statusText 说明 0** - 未被始化 1** - 请求收到,继续处理 100 Conti ...