flex_subtitle = "built using jupyter-flex"
flex_external_link = "https://github.com/danielfrg/jupyter-flex/blob/master/examples/iris-clustering.ipynb"
flex_title = "Iris K-Means Clustering"
flex_show_source = True
iris = datasets.load_iris()
options = [(fname, i) for i, fname in enumerate(iris.feature_names)]
x_label = widgets.Label(value="X Variable:")
x_var = widgets.Dropdown(options=options, value=0)
y_label = widgets.Label(value="Y Variable:")
y_var = widgets.Dropdown(options=options, value=1)
cluster_label = widgets.Label(value="Cluster count:")
cluster_count = widgets.BoundedIntText(value=3, min=1, max=9, disabled=False)
widgets.VBox([x_label, x_var, y_label, y_var, cluster_label, cluster_count])
def fit_model():
X = iris.data[:, [x_var.value, y_var.value]]
y = iris.target
estimator = KMeans(n_clusters=cluster_count.value)
estimator.fit(X)
return X, estimator
scale = cl.scales["3"]["qual"]["Set1"]
fig = go.FigureWidget()
plot = go.Scatter(x=[], y=[], mode="markers", marker=dict(color=[], colorscale=scale, size=10))
fig.add_trace(plot)
margin = go.layout.Margin(l=20, r=20, b=20, t=30)
fig = fig.update_layout(margin=margin)
def on_value_change(change):
X, estimator = fit_model()
fig.data[0]['x'] = X[:, 0]
fig.data[0]['y'] = X[:, 1]
fig.data[0]['marker']['color'] = estimator.labels_
scale = cl.scales[str(cluster_count.value)]["qual"]["Set1"] if cluster_count.value > 2 else None
fig.data[0]['marker']['colorscale'] = scale
fig.update_xaxes(title_text=x_var.label)
fig.update_yaxes(title_text=y_var.label)
x_var.observe(on_value_change, names='value')
y_var.observe(on_value_change, names='value')
cluster_count.observe(on_value_change, names='value')
on_value_change(None)
fig