kaknikhil commented on a change in pull request #433: Kmeans: Add automatic optimal cluster estimation URL: https://github.com/apache/madlib/pull/433#discussion_r320495479
########## 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': Review comment: We can use the global variable `SILHOUETTE`. This also applies to other uses of the hard coded value `silhouette` ---------------------------------------------------------------- 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: [email protected] With regards, Apache Git Services
