You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@madlib.apache.org by GitBox <gi...@apache.org> on 2019/09/04 18:26:30 UTC

[GitHub] [madlib] kaknikhil commented on a change in pull request #433: Kmeans: Add automatic optimal cluster estimation

kaknikhil commented on a change in pull request #433: Kmeans: Add automatic optimal cluster estimation
URL: https://github.com/apache/madlib/pull/433#discussion_r320881235
 
 

 ##########
 File path: src/ports/postgres/modules/kmeans/kmeans_auto.py_in
 ##########
 @@ -0,0 +1,201 @@
+# coding=utf-8
+#
+# 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.
+
+"""
+@file kmeans_auto.py_in
+
+@brief
+
+"""
+
+import numpy as np
+import math
+import plpy
+from utilities.utilities import _assert
+from utilities.utilities import unique_string
+from utilities.validate_args import output_tbl_valid
+from utilities.validate_args import get_algorithm_name
+
+ELBOW = 'elbow'
+SILHOUETTE = 'silhouette'
+BOTH = 'both'
+
+def _validate(output_table, k):
+
+    output_tbl_valid(output_table, "kmeans_auto")
+    output_tbl_valid(output_table+'_summary', "kmeans_auto")
+
+    _assert(k, "kmeans_auto: k cannot be NULL.")
+    _assert(len(k)>1, "kmeans_auto: there has to be more than 1 k values to consider.")
+    _assert(min(k)>1, "kmeans_auto: the minimum k value has to be > 1.")
+
+def set_defaults(schema_madlib, fn_dist, agg_centroid, max_num_iterations, min_frac_reassigned, k_selection_algorithm, seeding, seeding_sample_ratio):
+
+    fn_dist = (fn_dist if fn_dist is not None
+               else '{0}.squared_dist_norm2'.format(schema_madlib))
+    agg_centroid = (agg_centroid if agg_centroid is not None
+                    else '{0}.avg'.format(schema_madlib))
+    max_num_iterations = (max_num_iterations if max_num_iterations is not None
+                          else 20)
+    min_frac_reassigned = (min_frac_reassigned if min_frac_reassigned is not None
+                           else 0.001)
+
+    k_selection_algorithm = get_algorithm_name(k_selection_algorithm, ELBOW,
+        [ELBOW, SILHOUETTE, BOTH], 'kmeans_auto')
+
+    if seeding is 'pp':
+        seeding_sample_ratio = (seeding_sample_ratio
+                                if seeding_sample_ratio is not None else 1.0)
+    return (fn_dist, agg_centroid, max_num_iterations, min_frac_reassigned,
+            k_selection_algorithm, seeding_sample_ratio)
+
+def kmeans_auto(schema_madlib, rel_source, output_table, expr_point, k,
+    fn_dist=None, agg_centroid=None, max_num_iterations=None,
+    min_frac_reassigned=None, k_selection_algorithm=None, seeding=None,
+    seeding_sample_ratio=None, **kwargs):
+
+    _validate(output_table, k)
+
+    (fn_dist, agg_centroid, max_num_iterations, min_frac_reassigned,
+     k_selection_algorithm, seeding_sample_ratio) = set_defaults(
+        schema_madlib, fn_dist, agg_centroid, max_num_iterations,
+        min_frac_reassigned, k_selection_algorithm, seeding,
+        seeding_sample_ratio)
+
+    silhouette = ""
+    elbow = ""
+
+    plpy.execute("""
+        CREATE TABLE {output_table} (
+            k INTEGER,
+            centroids   DOUBLE PRECISION[][],
+            cluster_variance    DOUBLE PRECISION[],
+            objective_fn    DOUBLE PRECISION,
+            frac_reassigned DOUBLE PRECISION,
+            num_iterations  INTEGER)
+        """.format(**locals()))
+
+    silhouette_vals = []
+
+    for current_k in k:
+        if seeding is 'random':
+            plpy.execute("""
+                INSERT INTO {output_table}
+                SELECT {current_k} as k, *
+                FROM {schema_madlib}.kmeans_random('{rel_source}',
+                                     '{expr_point}',
+                                     {current_k},
+                                     '{fn_dist}',
+                                     '{agg_centroid}',
+                                     {max_num_iterations},
+                                     {min_frac_reassigned});
+                """.format(**locals()))
+        else:
+            plpy.execute("""
+                INSERT INTO {output_table}
+                SELECT {current_k} as k, *
+                FROM {schema_madlib}.kmeanspp('{rel_source}',
+                                     '{expr_point}',
+                                     {current_k},
+                                     '{fn_dist}',
+                                     '{agg_centroid}',
+                                     {max_num_iterations},
+                                     {min_frac_reassigned},
+                                     {seeding_sample_ratio});
+                """.format(**locals()))
+
+        if k_selection_algorithm != 'elbow':
+            silhouette_query= """
+                SELECT * FROM {schema_madlib}.simple_silhouette(
+                    '{rel_source}',
+                    '{expr_point}',
+                    (SELECT centroids
+                     FROM {output_table}
+                     WHERE k = {current_k}),
+                    '{fn_dist}')
+                """.format(**locals())
+            silhouette_vals.append(
+                plpy.execute(silhouette_query)[0]['simple_silhouette'])
+
+    # If the selection is silhouette or both, calculate silhouette
+    if k_selection_algorithm != 'elbow':
+
+        silhouette_vals_np = np.array(silhouette_vals)
+        optimal_sil =  k[np.argmax(silhouette_vals_np)]
+        silhouette = ", {0} AS silhouette".format(max(silhouette_vals))
+
+    # If the selection is elbow or both, calculate elbow
+    if k_selection_algorithm != 'silhouette':
+
+        index_with_elbow, second_order = _calculate_elbow(output_table)
+        optimal_elbow = index_with_elbow
+        elbow = ", {0} AS elbow".format(max(second_order))
+
+    optimal_k = (optimal_sil if k_selection_algorithm == 'silhouette'
+                 else optimal_elbow)
+
+    plpy.execute("""
+        CREATE TABLE {output_table}_summary AS
+        SELECT {output_table}.*,
+               '{k_selection_algorithm}'::VARCHAR AS selection_algorithm
+               {elbow}
+               {silhouette}
+        FROM {output_table}
+        WHERE k = {optimal_k}
+        """.format(**locals()))
+
+    return
+
+def _calculate_elbow(output_table):
+
+    # We have to get the values in ordered fashion because the elbow is only defined for ordered values.
+    inertia_result = plpy.execute("""
+                 SELECT k, objective_fn FROM {output_table} ORDER BY k ASC
+                 """.format(**locals()))
+    k = [ i['k'] for i in inertia_result ]
+    inertia_list = [ i['objective_fn'] for i in inertia_result ]
+    inertia_list = np.array(inertia_list)
+
+    #TODO: what to do if optimal is the very first (or last) value?
+    first_order=np.gradient(inertia_list, k)
+    second_order=np.gradient(first_order, k)
+    index_with_elbow=k[np.argmax(second_order)]
+
+    return index_with_elbow, second_order
+
+def kmeans_random_auto(schema_madlib, rel_source, output_table, expr_point, k,
+    fn_dist=None, agg_centroid=None, max_num_iterations=None,
+    min_frac_reassigned=None, k_selection_algorithm=None, **kwargs):
+
+    kmeans_auto(schema_madlib, rel_source, output_table, expr_point, k,
+    fn_dist, agg_centroid, max_num_iterations, min_frac_reassigned,
+    k_selection_algorithm, 'random')
 
 Review comment:
   Consider making variables for the strings 'random' and 'pp' which can then also be used in the `kmeans_auto` function.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services