读取文件的数据

使用的数据: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. fscanf使用

    函数名: fscanf 简述:C语言中基本的文件操作 功 能: 从一个流中执行格式化输入,fscanf遇到空格和换行时结束,注意空格时也结束.这与fgets有区别,fgets遇到空格不结束. 简单的说 ...

  2. redis非特定类型命令

    1. key查询 keys my* #获取当前数据库中符合模式的所有key exists mykey #查看key是否还存在 2. 数据库操作 redis默认一个实例的数据库是16个[db0-db15 ...

  3. Spring--通过注解来配置bean【转】

    Spring通过注解配置bean 基于注解配置bean 基于注解来配置bean的属性在classpath中扫描组件 组件扫描(component scanning):Spring能够从classpat ...

  4. 如何设置游戏分辨率(C++)

  5. T-SQL Recipes之生成动态列表数据

    Problem 首先什么是动态列表?举个示例,假设你想输出以逗号分隔的IDs,如: 1,45,67,199,298 Solution 生成动态列表数据在我们生活场景中很常见,比如在 Dynamic P ...

  6. MySQL-多条件拼接语句

    BEGIN "; SET @_where=""; THEN SET @_where= CONCAT(@_where," AND sourcedomain=\&q ...

  7. Python之路第一课Day1--随堂笔记

    课堂大纲: 一.Python介绍 二.发展史 三.Python 2 or 3? 四.安装 五.Hello World程序 六.变量 七.用户输入 八.模块初识 九..pyc是个什么鬼? 十.数据类型初 ...

  8. for循环

    1.使用for循环输出矩形 public static void print1(int h,int w){        for(int i=0; i<h; i++){            f ...

  9. ZK listbox 两种分页使用及比较

    参考:http://tsinglongwu.iteye.com/blog/849923 以下代码模拟数据量大时情况,采用“<paging>”组件方式 前台Listbox.zul : < ...

  10. Django入门实践(3)

    Django简单应用 前面简单示例说明了views和Template的工作过程,但是Django最核心的是App,涉及到App则会和Model(数据库)打交道.下面举的例子是创建一个简单应用wiki ...