Clustering - KMeans - Práctica inicial
Índice de contenido
python
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
import numpy as np
python
X = np.array([[1, 2],
[1, 4],
[1, 0],
[10, 2],
[10, 4],
[10, 0]])
python
df = pd.DataFrame(X, columns = ["xcoord", "ycoord"])
df
| xcoord | ycoord | |
|---|---|---|
| 0 | 1 | 2 |
| 1 | 1 | 4 |
| 2 | 1 | 0 |
| 3 | 10 | 2 |
| 4 | 10 | 4 |
| 5 | 10 | 0 |
python
plt.scatter(df.xcoord, df.ycoord)
<matplotlib.collections.PathCollection at 0xcfc5ee0>

python
knn = KMeans(n_clusters=2,
init='k-means++',
n_init=10,
tol=0.0001,
random_state=42,
algorithm='auto')
python
knn.fit(X)
KMeans(n_clusters=2, random_state=42)
python
knn.cluster_centers_
array([[10., 2.],
[ 1., 2.]])
python
df_centroides = pd.DataFrame(knn.cluster_centers_, columns = ["xcoord", "ycoord"])
df_centroides
| xcoord | ycoord | |
|---|---|---|
| 0 | 10.0 | 2.0 |
| 1 | 1.0 | 2.0 |
python
plt.scatter(df.xcoord, df.ycoord)
plt.scatter(df_centroides.xcoord, df_centroides.ycoord)
plt.scatter(df_newpoints.xcoord, df_newpoints.ycoord)
<matplotlib.collections.PathCollection at 0xd0c8040>

python
knn.inertia_
16.0
python
(4-2)**2 + (0-2)**2 + (4-2)**2 + (0-2)**2
16
python
knn.labels_
array([1, 1, 1, 0, 0, 0])
python
X
array([[ 1, 2],
[ 1, 4],
[ 1, 0],
[10, 2],
[10, 4],
[10, 0]])
python
knn.predict([[0, 0],
[12, 3]])
array([1, 0])
python
new_points = np.array([[0, 0],
[12, 3]])
new_points
array([[ 0, 0],
[12, 3]])
python
df_newpoints = pd.DataFrame(new_points, columns = ["xcoord", "ycoord"])
df_newpoints
| xcoord | ycoord | |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 12 | 3 |
