def run_gap_k_selection(data, k_min=<NUM_LIT:1>, k_max=<NUM_LIT:50>, B=<NUM_LIT:5>,<EOL>skip=<NUM_LIT:5>, **kwargs):
if k_min == k_max:<EOL><INDENT>return k_min<EOL><DEDENT>gap_vals = []<EOL>sk_vals = []<EOL>k_range = list(range(k_min, k_max, skip))<EOL>min_k = <NUM_LIT:0><EOL>min_i = <NUM_LIT:0><EOL>for i, k in enumerate(k_range):<EOL><INDENT>km = KMeans(k)<EOL>clusters = km.fit_predict(data)<EOL>gap, sk = calculate_gap(data, clusters, km, B=B)<EOL>if len(gap_vals) > <NUM_LIT:1>:<EOL><INDENT>if gap_vals[-<NUM_LIT:1>] >= gap - (skip+<NUM_LIT:1>)*sk:<EOL><INDENT>min_i = i<EOL>min_k = k_range[i-<NUM_LIT:1>]<EOL>break<EOL><DEDENT><DEDENT>gap_vals.append(gap)<EOL>sk_vals.append(sk)<EOL><DEDENT>if min_k == <NUM_LIT:0>:<EOL><INDENT>min_k = k_max<EOL><DEDENT>if skip == <NUM_LIT:1>:<EOL><INDENT>return min_k, gap_vals, sk_vals<EOL><DEDENT>gap_vals = []<EOL>sk_vals = []<EOL>for k in range(min_k - skip, min_k + skip):<EOL><INDENT>km = KMeans(k)<EOL>clusters = km.fit_predict(data)<EOL>gap, sk = calculate_gap(data, clusters, km, B=B)<EOL>if len(gap_vals) > <NUM_LIT:1>:<EOL><INDENT>if gap_vals[-<NUM_LIT:1>] >= gap - sk:<EOL><INDENT>min_k = k-<NUM_LIT:1><EOL>return min_k, gap_vals, sk_vals<EOL><DEDENT><DEDENT>gap_vals.append(gap)<EOL>sk_vals.append(sk)<EOL><DEDENT>return k, gap_vals, sk_vals<EOL>
Runs gap score for all k from k_min to k_max.