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 demonstrating k-means clustering.
0020 Run with:
0021   bin/spark-submit examples/src/main/python/ml/kmeans_example.py
0022 
0023 This example requires NumPy (http://www.numpy.org/).
0024 """
0025 from __future__ import print_function
0026 
0027 # $example on$
0028 from pyspark.ml.clustering import KMeans
0029 from pyspark.ml.evaluation import ClusteringEvaluator
0030 # $example off$
0031 
0032 from pyspark.sql import SparkSession
0033 
0034 if __name__ == "__main__":
0035     spark = SparkSession\
0036         .builder\
0037         .appName("KMeansExample")\
0038         .getOrCreate()
0039 
0040     # $example on$
0041     # Loads data.
0042     dataset = spark.read.format("libsvm").load("data/mllib/sample_kmeans_data.txt")
0043 
0044     # Trains a k-means model.
0045     kmeans = KMeans().setK(2).setSeed(1)
0046     model = kmeans.fit(dataset)
0047 
0048     # Make predictions
0049     predictions = model.transform(dataset)
0050 
0051     # Evaluate clustering by computing Silhouette score
0052     evaluator = ClusteringEvaluator()
0053 
0054     silhouette = evaluator.evaluate(predictions)
0055     print("Silhouette with squared euclidean distance = " + str(silhouette))
0056 
0057     # Shows the result.
0058     centers = model.clusterCenters()
0059     print("Cluster Centers: ")
0060     for center in centers:
0061         print(center)
0062     # $example off$
0063 
0064     spark.stop()