Back to home page

OSCL-LXR

 
 

    


0001 #
0002 # Licensed to the Apache Software Foundation (ASF) under one or more
0003 # contributor license agreements.  See the NOTICE file distributed with
0004 # this work for additional information regarding copyright ownership.
0005 # The ASF licenses this file to You under the Apache License, Version 2.0
0006 # (the "License"); you may not use this file except in compliance with
0007 # the License.  You may obtain a copy of the License at
0008 #
0009 #    http://www.apache.org/licenses/LICENSE-2.0
0010 #
0011 # Unless required by applicable law or agreed to in writing, software
0012 # distributed under the License is distributed on an "AS IS" BASIS,
0013 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014 # See the License for the specific language governing permissions and
0015 # limitations under the License.
0016 #
0017 
0018 """
0019 An example for summarizer.
0020 Run with:
0021   bin/spark-submit examples/src/main/python/ml/summarizer_example.py
0022 """
0023 from __future__ import print_function
0024 
0025 from pyspark.sql import SparkSession
0026 # $example on$
0027 from pyspark.ml.stat import Summarizer
0028 from pyspark.sql import Row
0029 from pyspark.ml.linalg import Vectors
0030 # $example off$
0031 
0032 if __name__ == "__main__":
0033     spark = SparkSession \
0034         .builder \
0035         .appName("SummarizerExample") \
0036         .getOrCreate()
0037     sc = spark.sparkContext
0038 
0039     # $example on$
0040     df = sc.parallelize([Row(weight=1.0, features=Vectors.dense(1.0, 1.0, 1.0)),
0041                          Row(weight=0.0, features=Vectors.dense(1.0, 2.0, 3.0))]).toDF()
0042 
0043     # create summarizer for multiple metrics "mean" and "count"
0044     summarizer = Summarizer.metrics("mean", "count")
0045 
0046     # compute statistics for multiple metrics with weight
0047     df.select(summarizer.summary(df.features, df.weight)).show(truncate=False)
0048 
0049     # compute statistics for multiple metrics without weight
0050     df.select(summarizer.summary(df.features)).show(truncate=False)
0051 
0052     # compute statistics for single metric "mean" with weight
0053     df.select(Summarizer.mean(df.features, df.weight)).show(truncate=False)
0054 
0055     # compute statistics for single metric "mean" without weight
0056     df.select(Summarizer.mean(df.features)).show(truncate=False)
0057     # $example off$
0058 
0059     spark.stop()