• 使用SGD算法逻辑回归的垃圾邮件分类器
 package com.oreilly.learningsparkexamples.scala

 import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.mllib.classification.LogisticRegressionWithSGD
import org.apache.spark.mllib.feature.HashingTF
import org.apache.spark.mllib.regression.LabeledPoint object MLlib { def main(args: Array[String]) {
val conf = new SparkConf().setAppName(s"MLlib example")
val sc = new SparkContext(conf) // Load 2 types of emails from text files: spam and ham (non-spam).
// Each line has text from one email.
val spam = sc.textFile("files/spam.txt")
val ham = sc.textFile("files/ham.txt") // Create a HashingTF instance to map email text to vectors of 100 features.
val tf = new HashingTF(numFeatures = 100)
// Each email is split into words, and each word is mapped to one feature.
val spamFeatures = spam.map(email => tf.transform(email.split(" ")))
val hamFeatures = ham.map(email => tf.transform(email.split(" "))) // Create LabeledPoint datasets for positive (spam) and negative (ham) examples.
val positiveExamples = spamFeatures.map(features => LabeledPoint(1, features))
val negativeExamples = hamFeatures.map(features => LabeledPoint(0, features))
val trainingData = positiveExamples ++ negativeExamples
trainingData.cache() // Cache data since Logistic Regression is an iterative algorithm. // Create a Logistic Regression learner which uses the SGD.
val lrLearner = new LogisticRegressionWithSGD()
// Run the actual learning algorithm on the training data.
val model = lrLearner.run(trainingData) // Test on a positive example (spam) and a negative one (ham).
// First apply the same HashingTF feature transformation used on the training data.
val posTestExample = tf.transform("O M G GET cheap stuff by sending money to ...".split(" "))
val negTestExample = tf.transform("Hi Dad, I started studying Spark the other ...".split(" "))
// Now use the learned model to predict spam/ham for new emails.
println(s"Prediction for positive test example: ${model.predict(posTestExample)}")
println(s"Prediction for negative test example: ${model.predict(negTestExample)}") sc.stop()
}
}
spam.txt
Dear sir, I am a Prince in a far kingdom you have not heard of.  I want to send you money via wire transfer so please ...
Get Viagra real cheap! Send money right away to ...
Oh my gosh you can be really strong too with these drugs found in the rainforest. Get them cheap right now ...
YOUR COMPUTER HAS BEEN INFECTED! YOU MUST RESET YOUR PASSWORD. Reply to this email with your password and SSN ...
THIS IS NOT A SCAM! Send money and get access to awesome stuff really cheap and never have to ...
ham.txt
Dear Spark Learner, Thanks so much for attending the Spark Summit 2014!  Check out videos of talks from the summit at ...
Hi Mom, Apologies for being late about emailing and forgetting to send you the package. I hope you and bro have been ...
Wow, hey Fred, just heard about the Spark petabyte sort. I think we need to take time to try it out immediately ...
Hi Spark user list, This is my first question to this list, so thanks in advance for your help! I tried running ...
Thanks Tom for your email. I need to refer you to Alice for this one. I haven't yet figured out that part either ...
Good job yesterday! I was attending your talk, and really enjoyed it. I want to try out GraphX ...
Summit demo got whoops from audience! Had to let you know. --Joe
  • maven打包scala程序
├── pom.xml
├── README.md
├── src
│ └── main
│ └── scala
│ └── com
│ └── learningsparkexamples
│ └── scala
│ └── MLlib.scala
MLlib.scala 就是上面写的scala代码,pom.xml 是 maven 编译时候的 配置 文件:
<?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>my.demo</groupId>
<artifactId>sparkdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<!--编译时候 java版本
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
-->
<encoding>UTF-8</encoding>
<scala.tools.version>2.10</scala.tools.version>
<!-- Put the Scala version of the cluster -->
<scala.version>2.10.5</scala.version>
</properties>
<dependencies>
<dependency> <!-- Spark dependency -->
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<version>1.6.1</version>
<scope>provided</scope>
</dependency>
<dependency> <!-- Spark dependency -->
<groupId>org.apache.spark</groupId>
<artifactId>spark-mllib_2.10</artifactId>
<version>1.6.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.10.5</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<!--用来编译scala的-->
<groupId>net.alchim31.maven</groupId>
<artifactId>
scala-maven-plugin</artifactId>
<version>3.1.5</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<executions>
<execution>
<id>scala-compile-first</id>
<phase>process-resources</phase>
<goals>
<goal>add-source</goal>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>scala-test-compile</id>
<phase>
process-test-resources</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
其中:
import org.apache.spark.{SparkConf, SparkContext}

所需要的依赖包配置是:

  <dependency> <!-- Spark dependency -->
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<version>1.6.1</version>
<scope>provided</scope>
</dependency>

 
import org.apache.spark.mllib.classification.LogisticRegressionWithSGD
import org.apache.spark.mllib.feature.HashingTF
import org.apache.spark.mllib.regression.LabeledPoint

所需要的依赖包配置是:

 <dependency> <!-- Spark dependency -->
<groupId>org.apache.spark</groupId>
<artifactId>spark-mllib_2.10</artifactId>
<version>1.6.1</version>
<scope>provided</scope>
</dependency>

配置的时候要注意spark 和 scala 的版本,可以打开spark-shell 观察:

配置完成后,在pom.xml 所在的目录运行命令:

mvn clean && mvn compile && mvn package

如果mvn 下载 有问题,可以参考这篇博文:http://www.cnblogs.com/xiaoyesoso/p/5489822.html 的 3. Bulid GitHub Spark Runnable Distribution

  • spark运行项目

mvn编译打包完成后会pom.xml所在目录下出现一个target文件夹:

├── target
│ ├── classes
│ │ └── com
│ │ └── oreilly
│ │ └── learningsparkexamples
│ │ └── scala
│ │ ├── MLlib$$anonfun$1.class
│ │ ├── MLlib$$anonfun$2.class
│ │ ├── MLlib$$anonfun$3.class
│ │ ├── MLlib$$anonfun$4.class
│ │ ├── MLlib.class
│ │ └── MLlib$.class
│ ├── classes.-475058802.timestamp
│ ├── maven-archiver
│ │ └── pom.properties
│ ├── maven-status
│ │ └── maven-compiler-plugin
│ │ └── compile
│ │ └── default-compile
│ │ ├── createdFiles.lst
│ │ └── inputFiles.lst
│ └── sparkdemo-1.0-SNAPSHOT.jar

最后 运行命令,提交执行任务(注意两个test文件所对应的位置):

${SPARK_HOME}/bin/spark-submit --class ${package.name}.${class.name} ${PROJECT_HOME}/target/*.jar

运行结果:

caizhenwei@caizhenwei-Inspiron-:~/桌面/learning-spark$ vim mini-complete-example/src/main/scala/com/oreilly/learningsparkexamples/mini/scala/MLlib.scala caizhenwei@caizhenwei-Inspiron-:~/桌面/learning-spark$ ../bin-spark-1.6./bin/spark-submit --class com.oreilly.learningsparkexamples.scala.MLlib ./mini-complete-example/target/sparkdemo-1.0-SNAPSHOT.jar
// :: WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
// :: WARN Utils: Your hostname, caizhenwei-Inspiron- resolves to a loopback address: 127.0.1.1; using 172.16.111.93 instead (on interface eth0)
// :: WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
// :: WARN Utils: Service 'SparkUI' could not bind on port . Attempting port .
// :: WARN BLAS: Failed to load implementation from: com.github.fommil.netlib.NativeSystemBLAS
// :: WARN BLAS: Failed to load implementation from: com.github.fommil.netlib.NativeRefBLAS
Prediction for positive test example: 1.0
Prediction for negative test example: 0.0

Spark MLlib + maven + scala 试水~的更多相关文章

  1. 十二、spark MLlib的scala示例

    简介 spark MLlib官网:http://spark.apache.org/docs/latest/ml-guide.html mllib是spark core之上的算法库,包含了丰富的机器学习 ...

  2. 朴素贝叶斯算法原理及Spark MLlib实例(Scala/Java/Python)

    朴素贝叶斯 算法介绍: 朴素贝叶斯法是基于贝叶斯定理与特征条件独立假设的分类方法. 朴素贝叶斯的思想基础是这样的:对于给出的待分类项,求解在此项出现的条件下各个类别出现的概率,在没有其它可用信息下,我 ...

  3. eclipse构建maven+scala+spark工程 转载

    转载地址:http://jingpin.jikexueyuan.com/article/47043.html 本文先叙述如何配置eclipse中maven+scala的开发环境,之后,叙述如何实现sp ...

  4. spark mllib配置pom.xml错误 Multiple markers at this line Could not transfer artifact net.sf.opencsv:opencsv:jar:2.3 from/to central (https://repo.maven.apache.org/maven2): repo.maven.apache.org

    刚刚spark mllib,在maven repository网站http://mvnrepository.com/中查询mllib后得到相关库的最新dependence为: <dependen ...

  5. spark Using MLLib in Scala/Java/Python

    Using MLLib in ScalaFollowing code snippets can be executed in spark-shell. Binary ClassificationThe ...

  6. Eclipse+maven+scala+spark环境搭建

    准备条件 我用的Eclipse版本 Eclipse Java EE IDE for Web Developers. Version: Luna Release (4.4.0) 我用的是Eclipse ...

  7. 梯度迭代树(GBDT)算法原理及Spark MLlib调用实例(Scala/Java/python)

    梯度迭代树(GBDT)算法原理及Spark MLlib调用实例(Scala/Java/python) http://blog.csdn.net/liulingyuan6/article/details ...

  8. 3 分钟学会调用 Apache Spark MLlib KMeans

    Apache Spark MLlib是Apache Spark体系中重要的一块拼图:提供了机器学习的模块.只是,眼下对此网上介绍的文章不是非常多.拿KMeans来说,网上有些文章提供了一些演示样例程序 ...

  9. Spark MLlib编程API入门系列之特征选择之卡方特征选择(ChiSqSelector)

    不多说,直接上干货! 特征选择里,常见的有:VectorSlicer(向量选择) RFormula(R模型公式) ChiSqSelector(卡方特征选择). ChiSqSelector用于使用卡方检 ...

随机推荐

  1. 梳理一下我理解的aop

    在看了很多网上的资料和记录之后,我大概捋了下SpringAOP的各种阶段: 基本的advice编程,利用ProxyFactory拿代理类 利用spring把ProxyFactory,advice等be ...

  2. Mysql 事务隔离级别(图文详解)

    本文由 SnailClimb 和 BugSpeak 共同完成. 事务隔离级别(图文详解) 什么是事务? 事物的特性(ACID) 并发事务带来的问题 事务隔离级别 实际情况演示 脏读(读未提交) 避免脏 ...

  3. Dubbo理论知识

    本文是作者根据官方文档以及自己平时的使用情况,对 Dubbo 所做的一个总结.如果不懂 Dubbo 的使用的话,可以参考我的这篇文章<超详细,新手都能看懂 !使用SpringBoot+Dubbo ...

  4. Spark无法创建新线程

    Spark提交程序报错,无法创建新的线程 原因是因为这台公用机器上跑的进程太多了,需要修改Linux参数,允许用户最大进程数 查看允许用户最大进程数配置 ulimit -a 修改允许用户最大进程数配置 ...

  5. Linux系统下安装rz/sz命令及使用说明(文件上传下载)

    1.安装软件 yum -y install lrzsz 2.本地文件上传命令 rz -bye 执行该命令后,在弹出框中选择要上传的文件即可 3.下载文件到本地 sz filename

  6. jQuery和AJAX基础

    jQuery和AJAX基础 jQuery 基础: 1.jQuery 选择器: 元素选择器:$("p"): #id 选择器:$("#test"): .class ...

  7. shell中使用ssh

    ssh服务是不能用非交互的方式传递密码,想不输入密码,直接ssh连接到服务器有两种方法,sshpass和expect sshpass # wget http://downloads.sourcefor ...

  8. -bash: mail: command not found

    近日,安装了一个最小化的centos 6.3 6,用mail发送邮件进行测试的时候提示-bash: mail: command not found mailx没有安装,于是: yum -y insta ...

  9. [Rational Rose 2007]解决启动报”解决无法启动此程序因为丢失suite objects.dll“的问题

    问题根源1:不是丢失suite objects.dll文件,而是环境变量配置错误或无配置 假如安装目录如:C:\Program Files\Rational 需要配置环境变量的路径为:C:\Progr ...

  10. 【Web应用-网络连接】Azure Web 应用对外连接数上限分析

    在 Azure Web 应用中发起大量外部连接操作时,需要考虑已经建立了多少外部连接.当超过最大对外连接数时,Azure Web 应用将会产生套接字异常.Azure Web 应用对于各个级别的实例,对 ...