Advertisement
EXTREMEXPLOIT

K_Means

Apr 11th, 2020
609
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. def kmeans(X, k):
  2.     def getDistance(P1, P2): return np.sqrt((P2[0] - P1[0])**2 + (P2[1] - P1[1])**2)
  3.     x_MIN, x_MAX, y_MIN, y_MAX = min(X[:, 0]), max(X[:, 0]), min(X[:, 1]), max(X[:, 1])
  4.     C = [(np.random.randint(x_MIN, x_MAX), np.random.randint(y_MIN, y_MAX)) for i in range(k)]
  5.     # Diccionario con clusters como clave y sus puntos asociados como valor:
  6.     clustersPoints = {i: [] for i in range(k)}
  7.     continueSearching = True
  8.     while continueSearching:
  9.         continueSearching = False
  10.         for dataPoint in X:
  11.             # Distancias entre nuestro punto y cada cluster:
  12.             clustersDistances = [getDistance(cluster, dataPoint) for cluster in C]
  13.             nearestCluster = clustersDistances.index(min(clustersDistances)) # Seleccionando el cluster más cercano.
  14.             clustersPoints[nearestCluster].append(dataPoint)
  15.         i = 0
  16.         for cluster in clustersPoints:
  17.             sumX, sumY = 0, 0
  18.             currentPoints = clustersPoints[cluster]
  19.             for currentPoint in currentPoints:
  20.                 sumX += currentPoint[0]
  21.                 sumY += currentPoint[1]
  22.             # Calculando las medias.
  23.             newCluster = sumX/len(currentPoints), sumY/len(currentPoints)
  24.             # Si el nuevo Cluster no está MUY cerca del anterior, actualizamos el cluster.
  25.             if getDistance(C[i], newCluster) > 0.001:
  26.                 C[i] = newCluster
  27.                 continueSearching = True
  28.             i += 1
  29.            
  30.     y = []
  31.     for clusterNumber in clustersPoints:
  32.         currentCluster = C[clusterNumber]
  33.         for clusterPoint in clustersPoints[clusterNumber]:
  34.             y.append([tuple(clusterPoint), currentCluster])
  35.            
  36.     return C, y
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement