Example 1: scikit learn k means
from sklearn.cluster import KMeans
df = np.array([[1,4],[2,2],[2,5],[3,3],[3,4],[4,7],[5,6],[6,4],[6,7],[7,6],[7,9],[8,7],[8,9],[9,4],[9,8]])
kmeans = KMeans(n_clusters=3, init='k-means++', max_iter=300, n_init=10)
y_pred = kmeans.fit_predict(df)
Example 2: k-means clustering python
from sklearn.cluster import KMeans
kmeans = KMeans(init="random", n_clusters=3, n_init=10, max_iter=300, random_state=42 )
kmeans.fit(x_train)
print(kmeans.inertia_)
print(kmeans.cluster_centers_)
print(kmeans.n_iter_)
print(kmeans.labels_[:5])
Example 3: grafica de clustering en 3d python
import plotly.plotly as py
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/alpha_shape.csv')
df.head()
scatter = dict(
mode = "markers",
name = "y",
type = "scatter3d",
x = df['x'], y = df['y'], z = df['z'],
marker = dict( size=2, color="rgb(23, 190, 207)" )
)
clusters = dict(
alphahull = 7,
name = "y",
opacity = 0.1,
type = "mesh3d",
x = df['x'], y = df['y'], z = df['z']
)
layout = dict(
title = '3d point clustering',
scene = dict(
xaxis = dict( zeroline=False ),
yaxis = dict( zeroline=False ),
zaxis = dict( zeroline=False ),
)
)
fig = dict( data=[scatter, clusters], layout=layout )
py.iplot(fig, filename='3d point clustering')