读取文件的数据

使用的数据:https://codeload.github.com/xsankar/fdps-v3/zip/master

读取单个文件的数据

case class Employee(EmployeeID: String,
LastName: String, FirstName: String, Title: String,
BirthDate: String, HireDate: String,
City: String, State: String, Zip: String, Country: String,
ReportsTo: String) def main(args: Array[String]): Unit = {
val conf = new SparkConf()
conf.set("spark.master", "local")
conf.set("spark.app.name", "spark demo")
val sc = new SparkContext(conf);
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
// 创建spark对象
val spark = SparkSession.builder().appName("spark sql").config(conf).getOrCreate(); import spark.implicits._ // 这行必须引入不然下面的报错
// header (default false): uses the first line as names of columns.
val employees = spark.read.option("header", "true")
.csv("hdfs://m3:9820/NW-Employees.csv").as[Employee]; employees.show(); }

 数据转换成一个视图,通过sql查询

case class Employee(EmployeeID: String,
LastName: String, FirstName: String, Title: String,
BirthDate: String, HireDate: String,
City: String, State: String, Zip: String, Country: String,
ReportsTo: String) def main(args: Array[String]): Unit = {
val conf = new SparkConf()
conf.set("spark.master", "local")
conf.set("spark.app.name", "spark demo")
val sc = new SparkContext(conf);
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
// 创建spark对象
val spark = SparkSession.builder().appName("spark sql").config(conf).getOrCreate(); import spark.implicits._ // 这行必须引入不然下面的报错
// header (default false): uses the first line as names of columns.
val employees = spark.read.option("header", "true")
.csv("hdfs://m3:9820/NW-Employees.csv").as[Employee];
// Creates a temporary view using the given name
employees.createOrReplaceTempView("employeesTable");
// 通过sql语句查询, 后面的表名不区分大小写
val records = spark.sql("select * from EmployeesTable");
records.show();
records.head(2);
records.explain(true); }

 join查询 

case class Order(OrderID: String,
CustomerID: String, EmployeeID: String, OrderDate: String,
ShipCountry: String) case class OrderDetail(OrderID: String,
ProductID: String, UnitPrice: String, Qty: String,
Discount: String) def main(args: Array[String]): Unit = {
val conf = new SparkConf()
conf.set("spark.master", "local")
conf.set("spark.app.name", "spark demo")
val sc = new SparkContext(conf);
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
// 创建spark对象
val spark = SparkSession.builder().appName("spark sql").config(conf).getOrCreate(); import spark.implicits._ // 这行必须引入不然下面的报错
// header (default false): uses the first line as names of columns.
val orders = spark.read.option("header", "true")
.csv("hdfs://m3:9820/NW-Orders.csv").as[Order];
val orderDetails = spark.read.option("header", "true")
.csv("hdfs://m3:9820/NW-Order-Details.csv").as[OrderDetail];
// Creates a temporary view using the given name
orders.createOrReplaceTempView("orders")
orderDetails.createOrReplaceTempView("orderDetails")
// show 方法如果不显示的指定显示多少行,则默认显示20行
// orders.show();
// orderDetails.show();
// 如果对表不指定别名,则别名和表明一样
val joinResult = spark.sql("select o.OrderID, orderDetails.ProductID from orders o inner join orderDetails on o.OrderID = orderDetails.OrderID")
joinResult.show }

 数据的读取和写出 

def main(args: Array[String]): Unit = {
val conf = new SparkConf()
conf.set("spark.master", "local")
conf.set("spark.app.name", "spark demo")
val sc = new SparkContext(conf);
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
// 创建spark对象
val spark = SparkSession.builder().appName("spark sql").config(conf).getOrCreate(); import spark.implicits._ // 这行必须引入不然下面的报错
// header (default false): uses the first line as names of columns.
// inferSchema (default `false`): infers the input schema automatically from data. It
// requires one extra pass over the data.
// read data from file
val cars = spark.read.option("header", "true").option("inferSchema", "true")
.csv("hdfs://m3:9820/cars.csv");
cars.show(5)
cars.printSchema() // write data to file
// overwrite 覆盖原来的数据
// csv 保存数据
cars.write.mode("overwrite").option("header", "true").csv("hdfs://m3:9820/cars_csv") // parquet 格式存储数据
cars.write.mode("overwrite").partitionBy("year").parquet("hdfs://m3:9820/cars_parquet")
}

 统计方法

def main(args: Array[String]): Unit = {
val conf = new SparkConf()
conf.set("spark.master", "local")
conf.set("spark.app.name", "spark demo")
val sc = new SparkContext(conf);
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
// 创建spark对象
val spark = SparkSession.builder().appName("spark sql").config(conf).getOrCreate(); import spark.implicits._ // 这行必须引入不然下面的报错
// header (default false): uses the first line as names of columns.
// inferSchema (default `false`): infers the input schema automatically from data. It
// requires one extra pass over the data.
// read data from file
val cars = spark.read.option("header", "true").option("inferSchema", "true")
.csv("hdfs://m3:9820/cars.csv");
cars.show(5)
cars.printSchema() // 显示某一列的最大值、最小值、平均值、标准偏差
cars.describe("model").show() // groupBy 分组 avg 求平均值
cars.groupBy("year").avg("year").show()
cars.show() }

  

def main(args: Array[String]): Unit = {
val conf = new SparkConf()
conf.set("spark.master", "local")
conf.set("spark.app.name", "spark demo")
val sc = new SparkContext(conf);
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
// 创建spark对象
val spark = SparkSession.builder().appName("spark sql").config(conf).getOrCreate(); import spark.implicits._ // 这行必须引入不然下面的报错
// header (default false): uses the first line as names of columns.
// inferSchema (default `false`): infers the input schema automatically from data. It
// requires one extra pass over the data.
// read data from file
val passagers = spark.read.option("header", "true").option("inferSchema", "true")
.csv("hdfs://m3:9820/titanic3_02.csv"); // Pclass,Survived,Name,Gender,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked,Boat,Body,HomeDest
// 选择dataset里面的一些列,生成新的dataset
val passagers1 = passagers.select(passagers("Pclass"), passagers("Survived"),
passagers("Gender"), passagers("Age"), passagers("SibSp"),
passagers("Parch"), passagers("Fare")) passagers1.show passagers1.printSchema() passagers1.groupBy("Gender").count.show passagers1.stat.crosstab("Survived", "SibSp").show }

 线性回归 

def main(args: Array[String]): Unit = {
val conf = new SparkConf()
//conf.set("spark.master", "spark://m2:7077")
conf.set("spark.master", "local[4]")
// 创建SparkSession对象
val spark = SparkSession.builder().appName("spark sql").config(conf).getOrCreate();
// 创建sparkContext对象
// val sc = spark.sparkContext
// inferSchema为true可以自动推测数据的类型,默认false,则所有的数据都是String类型的
// 1、加载数据
val cars = spark.read.option("header", "true").option("inferSchema", "true").csv("hdfs://m2:9820/car-milage.csv")
/*cars.show(5)
cars.printSchema() // mpg|displacement| hp|torque|CRatio|RARatio|CarbBarrells|NoOfSpeed|length|width|weight|automatic|
cars.describe("mpg", "hp", "weight", "automatic").show val corr = cars.stat.corr("hp", "weight")
println("correlation is %2.4f".format(corr)) val cov = cars.stat.cov("hp", "weight")
// 协方差
println("covariance is %2.4f".format(cov))*/ // Returns a new [[DataFrame]] that drops rows containing any null or NaN values.
val cars1 = cars.na.drop() // 2、创建一个向量
val assembler = new VectorAssembler() // 设置输入
assembler.setInputCols(Array("displacement", "hp", "torque", "CRatio",
"RARatio", "CarbBarrells" ,"NoOfSpeed" ,"length", "width" , "weight" ,"automatic"
))
// 设置输出
assembler.setOutputCol("features") // 转换
val cars2 = assembler.transform(cars1)
// cars2.show(); // 3、分类数据 val train = cars2.filter(cars2("weight") <= 4000) val test = cars2.filter(cars2("weight") > 4000) // test.show
// 4、设置线性回归的一些参数
val linearReg = new LinearRegression
// Set the maximum number of iterations(迭代)
linearReg.setMaxIter(100)
// Set the regularization(正则化) parameter
linearReg.setRegParam(0.3)
// Set the ElasticNet mixing parameter
// L2 (ridge regression)
// - L1 (Lasso)
// L2 + L1 (elastic net)
// 默认是0 L2(ridge regression), 0 L2, 1 L1(Lasso) 大于0小于1是L2 + L1
linearReg.setElasticNetParam(0.8)
linearReg.setLabelCol("mpg") // 这个就是被预测的值得label // println("train count: " + train.count())
// 5、对数据进行训练
val mdlLR = linearReg.fit(train) println("totalIterations: " + mdlLR.summary.totalIterations) // 6、根据训练模型预测数据(prediction)
val predictions = mdlLR.transform(test)
predictions.show
val evaluator = new RegressionEvaluator
evaluator.setLabelCol("mpg")
val rmse = evaluator.evaluate(predictions)
// rmse root mean squared error
println("root mean squared error = " + "%6.3f".format(rmse)) evaluator.setMetricName("mse")
val mse = evaluator.evaluate(predictions)
// mean squared error
println("mean squared error = " + "%6.3f".format(mse))
}

 分类

def main(args: Array[String]): Unit = {
val conf = new SparkConf()
conf.set("spark.master", "spark://m2:7077")
// conf.set("spark.master", "local[8]")
// 创建SparkSession对象
val spark = SparkSession.builder().appName("spark sql").config(conf).getOrCreate();
// 创建sparkContext对象
// val sc = spark.sparkContext
// inferSchema为true可以自动推测数据的类型,默认false,则所有的数据都是String类型的
// 1、加载数据
val passagers = spark.read.option("header", "true").option("inferSchema", "true")
.csv("hdfs://m2:9820/titanic3_02.csv")
// passagers.show()
// passagers.printSchema() // 2、提取特征
val passagers1 = passagers.select(passagers("Pclass"), passagers("Survived").cast(DoubleType).as("Survived"),
passagers("Gender"), passagers("Age"), passagers("SibSp"), passagers("Parch")
, passagers("Fare")) // VectorAssembler 不支持字符串类型,转换Gender为数字类型
val indexer = new StringIndexer
indexer.setInputCol("Gender")
indexer.setOutputCol("GenderCat")
val passagers2 = indexer.fit(passagers1).transform(passagers1)
// passagers2.show // 删除包含null或者NAN的行
val passagers3 = passagers2.na.drop()
println("total count:" + passagers2.count() + " droped count is: " + (passagers2.count() - passagers3.count())) val vectorAssembler = new VectorAssembler
vectorAssembler.setInputCols(Array("Pclass", "GenderCat", "Age", "SibSp", "Parch", "Fare"))
vectorAssembler.setOutputCol("features")
val passagers4 = vectorAssembler.transform(passagers3)
// passagers4.show() // 3、数据分类,分为训练数据和测试数据 val Array(train, test) = passagers4.randomSplit(Array(0.9, 0.1))
// train.show() val algtree = new DecisionTreeClassifier
algtree.setLabelCol("Survived")
algtree.setImpurity("gini")
algtree.setMaxBins(32)
// Maximum depth of the tree
algtree.setMaxDepth(5) // 模型
val mdlTree = algtree.fit(train)
// println(mdlTree.toDebugString)
// println(mdlTree.toString)
// println(mdlTree.featureImportances) //4、 利用模型评估
val predictions = mdlTree.transform(test)
predictions.show // 5、模型评估
val evaluator = new MulticlassClassificationEvaluator
evaluator.setLabelCol("Survived")
// metric(度量标准) name in evaluation
// (supports `"f1"` (default), `"weightedPrecision"`,`"weightedRecall"`, `"accuracy"`)
evaluator.setMetricName("accuracy")
val accuracy = evaluator.evaluate(predictions)
println("the accuracy is %.2f%%".format(accuracy)) }

  

聚类

def main(args: Array[String]): Unit = {
val conf = new SparkConf()
conf.set("spark.master", "local[4]")
// conf.set("spark.master", "local[8]")
// 创建SparkSession对象
val spark = SparkSession.builder().appName("spark sql").config(conf).getOrCreate();
// 创建sparkContext对象
// val sc = spark.sparkContext
// inferSchema为true可以自动推测数据的类型,默认false,则所有的数据都是String类型的
// 1、加载数据
val points = spark.read.option("header", "true").option("inferSchema", "true")
.csv("hdfs://m2:9820/cluster-points-v2.csv")
// points.show()
// points.printSchema() // 2、数据转换
val vectorAssembler = new VectorAssembler
vectorAssembler.setInputCols(Array("X", "Y"))
vectorAssembler.setOutputCol("features")
val points1 = vectorAssembler.transform(points)
// points1.show()
// points1.printSchema() // 3、聚类是一个非监督学习算法,不需要把数据分为train和test,这里是用k-means算法
// key值(2)代表有多少个cluster
val algKmeans = new KMeans().setK(2)
// 模型
val mdlKmeans = algKmeans.fit(points1) // 4、利用模型预测
val predictions = mdlKmeans.transform(points1)
// predictions.show
// 5、评估 wsse 每个cluster中点到cluster中心的距离之和,越小越好
val wsse = mdlKmeans.computeCost(points1)
println(wsse) }

  推荐

def parseRating(row: Row): Rating = {
val aList = row.getList[String](0)
Rating(aList.get(0).toInt, aList.get(1).toInt, aList.get(2).toDouble) //.getInt(0), row.getInt(1), row.getDouble(2))
} def rowSqDiff(row:Row) : Double = {
math.pow( (row.getDouble(2) - row.getFloat(3).toDouble),2)
} def main(args: Array[String]): Unit = {
val conf = new SparkConf()
conf.set("spark.master", "local[4]")
// conf.set("spark.master", "local[8]")
// 创建SparkSession对象
val spark = SparkSession.builder().appName("spark sql").config(conf).getOrCreate();
// 创建sparkContext对象
// val sc = spark.sparkContext
// inferSchema为true可以自动推测数据的类型,默认false,则所有的数据都是String类型的
val startTime = System.nanoTime()
// 1、加载数据 val movies = spark.read.text("hdfs://m3:9820/movies.dat")
// movies.show()
// movies.printSchema() val ratings = spark.read.text("hdfs://m3:9820/ratings.dat")
// ratings.show()
// ratings.printSchema() val users = spark.read.text("hdfs://m3:9820/users.dat")
// users.show()
// users.printSchema() val ratings1 = ratings.select(split(ratings("value"), "::")).as("values")
// ratings1.show
// 2、数据转换 Rating
val rating2 = ratings1.rdd.map(parseRating(_))
val rating3 = spark.createDataFrame(rating2)
// rating3.show // 3、数据分为train和test
val Array(train, test) = rating3.randomSplit(Array(0.8, 0.2)) // 4、构建模型,训练数据
val algAls = new ALS
algAls.setItemCol("product")
algAls.setRank(12)
algAls.setRegParam(0.1) // 正则化参数
algAls.setMaxIter(20)
// 模型
val mdlReco = algAls.fit(train) // mdlReco.
// 5、预测数据
val predictions = mdlReco.transform(test)
predictions.show
predictions.printSchema() // 6、算法评估
// 过滤一些NAN数据
val nanState = predictions.na.fill(99999.0)
println(nanState.filter(nanState("prediction") > 99998).count())
nanState.filter(nanState("prediction") > 99998).show(5)
//
val pred = predictions.na.drop()
println("Orig = "+predictions.count()+" Final = "+ pred.count() + " Dropped = "+ (predictions.count() - pred.count()))
// Calculate RMSE & MSE
val evaluator = new RegressionEvaluator()
evaluator.setLabelCol("rating")
var rmse = evaluator.evaluate(pred)
println("Root Mean Squared Error = "+"%.3f".format(rmse))
//
evaluator.setMetricName("mse")
var mse = evaluator.evaluate(pred)
println("Mean Squared Error = "+"%.3f".format(mse))
mse = pred.rdd.map(r => rowSqDiff(r)).reduce(_+_) / predictions.count().toDouble
println("Mean Squared Error (Calculated) = "+"%.3f".format(mse))
//
//
val elapsedTime = (System.nanoTime() - startTime) / 1e9
println("Elapsed time: %.2f seconds".format(elapsedTime)) // MatrixFactorizationModel
}

  

spark 基本操作的更多相关文章

  1. spark 基本操作(二)

    1.dataframe 基本操作 def main(args: Array[String]): Unit = { val spark = SparkSession.builder() .appName ...

  2. spark 基本操作整理

    关于spark 的详细操作请参照spark官网 scala 版本:2.11.8 1.添加spark maven依赖,如需访问hdfs,则添加hdfs依赖 groupId = org.apache.sp ...

  3. Spark数据分析-记录关联问题

    1. 问题描述 记录关联问题(Record Linkage):有大量从一个或多个源系统来的记录,其中有些记录可能代表了相同的基础实体. 每个实体有若干个属性,比如姓名.地址.生日.我们需要根据这些属性 ...

  4. Spark安装部署(local和standalone模式)

    Spark运行的4中模式: Local Standalone Yarn Mesos 一.安装spark前期准备 1.安装java $ sudo tar -zxvf jdk-7u67-linux-x64 ...

  5. Spark RDD/Core 编程 API入门系列 之rdd实战(rdd基本操作实战及transformation和action流程图)(源码)(三)

    本博文的主要内容是: 1.rdd基本操作实战 2.transformation和action流程图 3.典型的transformation和action RDD有3种操作: 1.  Trandform ...

  6. Spark Streaming 基本操作

    Spark Streaming 基本操作 ​ 一.案例引入        3.1 StreamingContext        3.2 数据源        3.3 服务的启动与停止二.Transf ...

  7. Spark笔记:RDD基本操作(下)

    上一篇里我提到可以把RDD当作一个数组,这样我们在学习spark的API时候很多问题就能很好理解了.上篇文章里的API也都是基于RDD是数组的数据模型而进行操作的. Spark是一个计算框架,是对ma ...

  8. Spark笔记:RDD基本操作(上)

    本文主要是讲解spark里RDD的基础操作.RDD是spark特有的数据模型,谈到RDD就会提到什么弹性分布式数据集,什么有向无环图,本文暂时不去展开这些高深概念,在阅读本文时候,大家可以就把RDD当 ...

  9. Kafka:ZK+Kafka+Spark Streaming集群环境搭建(十八)ES6.2.2 增删改查基本操作

    #文档元数据 一个文档不仅仅包含它的数据 ,也包含 元数据 —— 有关 文档的信息. 三个必须的元数据元素如下:## _index    文档在哪存放 ## _type    文档表示的对象类别 ## ...

随机推荐

  1. SSM框架整合首只拦路虎——Eclipse新建Maven Project界面select an archetype 空白

    首先给大家说,本篇博客没有技术价值,纯属个人学习总结,权当给大家添加一乐.事件如有雷同,纯属巧合,莫怪! 前一段时间一直在看<淘淘商城>这个教程,里面讲的是SSM框架的一个电商项目.这不是 ...

  2. canvas画布属性globalAlpha 和 createRadialGradient函数出现的设置问题

    今天用canvas做了一个页面特效,呼呼,在做的过程中发现createRadialGradient 和 globalAlpha这2个属性一起使用导入不能实现透明度问题,首先把createRadialG ...

  3. Bug整理——$(window).height()获取到$(document).height()的问题

    想看解决方案不想看无聊乏味的bug解决过程的同学,请直接跳转到页面底部~ 今天在做项目的过程中遇到了一个BUG,项目中需要获取到浏览器客户区的高度以方便做一些适应性调整,代码如下: $(documen ...

  4. VB下对HTML元素的操作

    <!DOCTYPE html> <html> <head> <title>test</title> </head> <bo ...

  5. 在docker 中配置hadoop1.2.1 cluser

    最近一直在找工作,比较空闲,就没事研究一下hadoop,网上的视频及书,讲的差不多都是1.2.1这个版本,然后就试着在docker中搭建了一个hadoop集群, 项目已经放到了github上面了,供新 ...

  6. jenkins,dns错误log过大

    http://stackoverflow.com/questions/31719756/how-to-stop-jenkins-log-from-becoming-huge Recently my j ...

  7. maven模块

    用maven无它,唯方便而. 模块依赖可以用来做一些公共模块,多个工程调用. 先子模块 install 或者package.在父模块install

  8. linux软件包管理(下)

    在vi配置文件的编写的时候我们发现#并不能注释掉一行的信息 那什么才是linux标准的注释信息呢 查看软件对应的软件包命令 rpm –ap| grep vim 大多example是需要的事例文档  双 ...

  9. 在Unity中使用TDD - 初探

    描述 Editor Tests Runner是Unity中用来实现TDD的,其内部实现是基于NUnit. 其他 测试脚本要放在Editor文件夹中,测试要能够在一帧的时间内完成. 使用 打开Edito ...

  10. CSS3过渡、变形和动画

    1.CSS3过渡 所谓CSS3过渡,就是使用CSS3让元素从一种状态慢慢转换到另一种状态.如鼠标的悬停状态就是一种过渡.如下例子: #content a{     text-decoration: n ...