Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-13672] [ML] Add python examples of BisectingKMeans in ML and MLLIB #11515

Closed
wants to merge 12 commits into from
60 changes: 60 additions & 0 deletions examples/src/main/python/ml/bisecting_k_means_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from __future__ import print_function

from pyspark import SparkContext
# $example on$
from pyspark.ml.clustering import BisectingKMeans, BisectingKMeansModel
from pyspark.mllib.linalg import VectorUDT, _convert_to_vector, Vectors
# $example off$
from pyspark.sql import SQLContext

"""
A simple example demonstrating a bisecting k-means clustering.
"""

if __name__ == "__main__":

sc = SparkContext(appName="PythonBisectingKMeansExample")
sqlContext = SQLContext(sc)

# $example on$
training = sqlContext.createDataFrame([
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we make this example more consistent with the style of the other one (and the ML kmeans example):

from pyspark.sql.types import Row
from pyspark.mllib.linalg import Vectors
...
data = sc.textFile("data/mllib/kmeans_data.txt")
parsedData = data.map(lambda line: Row(features=Vectors.dense([float(x) for x in line.split(' ')])))
training = sqlContext.createDataFrame(parsedData)
...

(0, Vectors.dense(0.1, 0.1, 0.1)),
(1, Vectors.dense(0.3, 0.3, 0.25)),
(2, Vectors.dense(0.1, 0.1, -0.1)),
(3, Vectors.dense(20.3, 20.1, 19.9)),
(4, Vectors.dense(20.2, 20.1, 19.7)),
(5, Vectors.dense(18.9, 20.0, 19.7))], ["id", "features"])

k = 2
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can just make this kmeans = BisectingKMeans().setK(2).setSeed(1).setFeaturesCol("features")

kmeans = BisectingKMeans().setK(k).setSeed(1).setFeaturesCol("features")

model = kmeans.fit(training)

# Evaluate clustering
cost = model.computeCost(training)
print("Bisecting K-means Cost = " + str(cost))

centers = model.clusterCenters()
print("Cluster Centers: ")
for center in centers:
print(center)
# $example off$

sc.stop()
51 changes: 51 additions & 0 deletions examples/src/main/python/mllib/bisecting_k_means_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from __future__ import print_function

# $example on$
from numpy import array
from math import sqrt
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this import is no longer required

# $example off$

from pyspark import SparkContext
# $example on$
from pyspark.mllib.clustering import BisectingKMeans, BisectingKMeansModel
# $example off$

if __name__ == "__main__":
sc = SparkContext(appName="PythonBisectingKMeansExample") # SparkContext

# $example on$
# Load and parse the data
data = sc.textFile("data/mllib/kmeans_data.txt")
parsedData = data.map(lambda line: array([float(x) for x in line.split(' ')]))

# Build the model (cluster the data)
clusters = BisectingKMeans.train(parsedData, 2, maxIterations=5)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we call this model to match ML example?


# Evaluate clustering
cost = clusters.computeCost(parsedData)
print("Bisecting K-means Cost = " + str(cost))

# Save and load model
path = "target/org/apache/spark/PythonBisectingKMeansExample/BisectingKMeansModel"
clusters.save(sc, path)
sameModel = BisectingKMeansModel.load(sc, path)
# $example off$

sc.stop()
1 change: 1 addition & 0 deletions python/pyspark/mllib/clustering.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ class BisectingKMeans(object):
.. versionadded:: 2.0.0
"""

@classmethod
@since('2.0.0')
def train(self, rdd, k=4, maxIterations=20, minDivisibleClusterSize=1.0, seed=-1888008604):
"""
Expand Down