# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/khbae/trading/blob/master/k_means_clustering.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + [markdown] id="IClCrRuj6UrL" colab_type="text"
# ## K-means clustering
#
# https://en.wikipedia.org/wiki/K-means_clustering

# + id="eykCWCac5-Hx" colab_type="code" colab={}
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
# %matplotlib inline

# + id="BYPxIUFC5-H1" colab_type="code" colab={}
#Generating Data
Ax=60+8*np.random.normal(size=100)
Ay=80+8*np.random.normal(size=100)
Bx=20+7*np.random.normal(size=88)
By=120+7*np.random.normal(size=88)
Cx=20+10*np.random.normal(size=66)
Cy=30+10*np.random.normal(size=66)

X=np.concatenate([Ax,Bx,Cx])
Y=np.concatenate([Ay,By,Cy])
data=list(zip(X,Y))

# + id="OvSlE64e5-H4" colab_type="code" outputId="4d28af0b-60bf-456d-cffe-075313828669" colab={"base_uri": "https://localhost:8080/", "height": 283}
plt.scatter(X,Y)

# + id="XYUj6Mkn5-H-" colab_type="code" outputId="66f5d8b1-e0ec-4bac-a443-b8ad39c007ce" colab={"base_uri": "https://localhost:8080/", "height": 225}
#instantiate the model
kmeans=KMeans(n_clusters=3)
#fitting the model
kmeans.fit(data)

print("centers of clusters\n",kmeans.cluster_centers_)
print("labels of data\n",kmeans.labels_)

# + id="YjCOg1rl5-IC" colab_type="code" outputId="168f427d-8cfe-47ca-8866-802f4a4a7ad3" colab={"base_uri": "https://localhost:8080/", "height": 283}
#plot by labels
len_labels=len(kmeans.labels_)
Rx=[X[i] for i in range(len_labels) if kmeans.labels_[i]==0]
Ry=[Y[i] for i in range(len_labels) if kmeans.labels_[i]==0]
Gx=[X[i] for i in range(len_labels) if kmeans.labels_[i]==1]
Gy=[Y[i] for i in range(len_labels) if kmeans.labels_[i]==1]
Bx=[X[i] for i in range(len_labels) if kmeans.labels_[i]==2]
By=[Y[i] for i in range(len_labels) if kmeans.labels_[i]==2]
center_x=[i[0] for i in kmeans.cluster_centers_]
center_y=[i[1] for i in kmeans.cluster_centers_]

plt.figure(1)
plt.scatter(Rx,Ry,color='red')
plt.scatter(Gx,Gy,color='green')
plt.scatter(Bx,By,color='blue')
plt.scatter(center_x,center_y,marker="x",color="black",s=100)

# + id="p5vNziDe5-IG" colab_type="code" colab={}


StarcoderdataJupyterScriptsDedupFiltered