Randomly choose k data points as initial centroids
966878
def get_initial_centroids(self):
        ''''''
        if self.seed is not None: # useful for obtaining consistent results
            np.random.seed(self.seed)
        n = self.data.shape[0] # number of data points
        
        # Pick K indices from range [0, N).
        rand_indices = np.random.randint(0, n, self.k)
    
        # Keep centroids as dense format, as many entries will be nonzero due to averaging.
        # As long as at least one document in a cluster contains a word,
        # it will carry a nonzero weight in the TF-IDF vector of the centroid.
        centroids = self.data[rand_indices,:].toarray()
        self.centroids=centroids
        return centroids
641275
def _kmedoids_run(X, n_clusters, distance, max_iter, tol, rng):
    
    membs = np.empty(shape=X.shape[0], dtype=int)
    centers = kmeans._kmeans_init(X, n_clusters, method='', rng=rng)

    sse_last = 9999.9
    n_iter = 0
    for it in range(1,max_iter):
        membs = kmeans._assign_clusters(X, centers)
        centers,sse_arr = _update_centers(X, membs, n_clusters, distance)
        sse_total = np.sum(sse_arr)
        if np.abs(sse_total - sse_last) < tol:
            n_iter = it
            break
        sse_last = sse_total

    return(centers, membs, sse_total, sse_arr, n_iter)
382158
def _new_centroid(x, n, cumn)
      c = Centroid.new(x, n, cumn)
      @centroids[x] = c
      c
    end
268993
def _kmeans_run(X, n_clusters, max_iter, tol):
    
    membs = np.empty(shape=X.shape[0], dtype=int)
    centers = _kmeans_init(X, n_clusters)

    sse_last = 9999.9
    n_iter = 0
    for it in range(1,max_iter):
        membs = _assign_clusters(X, centers)
        centers,sse_arr = _update_centers(X, membs, n_clusters)
        sse_total = np.sum(sse_arr)
        if np.abs(sse_total - sse_last) < tol:
            n_iter = it
            break
        sse_last = sse_total

    return(centers, membs, sse_total, sse_arr, n_iter)
557598
def _k_modes_iter(X, centroids, cl_attr_freq, membship, dissim, random_state):
    """"""
    moves = 0
    for ipoint, curpoint in enumerate(X):
        clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
        if membship[clust, ipoint]:
            # Point is already in its right place.
            continue

        # Move point, and update old/new cluster frequencies and centroids.
        moves += 1
        old_clust = np.argwhere(membship[:, ipoint])[0][0]

        cl_attr_freq, membship, centroids = move_point_cat(
            curpoint, ipoint, clust, old_clust, cl_attr_freq, membship, centroids
        )

        # In case of an empty cluster, reinitialize with a random point
        # from the largest cluster.
        if not membship[old_clust, :].any():
            from_clust = membship.sum(axis=1).argmax()
            choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
            rindx = random_state.choice(choices)

            cl_attr_freq, membship, centroids = move_point_cat(
                X[rindx], rindx, old_clust, from_clust, cl_attr_freq, membship, centroids
            )

    return centroids, moves
45448
function init() {
  shift++;
  samples = new SamplePoints();
  samples.setBounds( new Rectangle( 25, 25 ).size( space.size.x - 25, space.size.y - 25 ), true );
  samples.poissonSampler( 6 ); // target 6px radius
}
942048
def _rand_init(x_bounds, x_types, selection_num_starting_points):
    '''
    
    '''
    return [lib_data.rand(x_bounds, x_types) for i \
                    in range(0, selection_num_starting_points)]
1099110
private double getRandomNeighbor(T[] data, T[] medoids, int[] y, double[] d) {
        int n = data.length;

        int index = Math.randomInt(k);
        T medoid = null;
        boolean dup;
        do {
            dup = false;
            medoid = data[Math.randomInt(n)];
            for (int i = 0; i < k; i++) {
                if (medoid == medoids[i]) {
                    dup = true;
                    break;
                }
            }
        } while (dup);

        medoids[index] = medoid;

        for (int i = 0; i < n; i++) {
            double dist = distance.d(data[i], medoid);
            if (d[i] > dist) {
                y[i] = index;
                d[i] = dist;
            } else if (y[i] == index) {
                d[i] = dist;
                y[i] = index;
                for (int j = 0; j < k; j++) {
                    if (j != index) {
                        dist = distance.d(data[i], medoids[j]);
                        if (d[i] > dist) {
                            y[i] = j;
                            d[i] = dist;
                        }
                    }
                }
            }
        }

        return Math.sum(d);
    }
86689
private void setMeanDistancesToCentroids() {
        meanDistancesToCentroids = new HashMap<>();
        for (int i = 0; i < clusterCentroids.numInstances(); i++) {    //For each centroid
            int countAssignedInstances = 0;
            double sumDistancesToCentroid = 0.0;
            Instance centroidInstance = clusterCentroids.instance(i);
            for (int j = 0; j < trainingData.numInstances(); j++) {       //For each data point
                 if (i == centroidAssignments[j]) {
                     Instance valueInstance = trainingData.instance(j);
                     double distanceToCentroid = Math.abs(valueInstance.value(0) -
                                                    centroidInstance.value(0));
                     sumDistancesToCentroid += distanceToCentroid;
                     countAssignedInstances++;
                 }
            }
            double meanDistanceToCentroid = sumDistancesToCentroid / countAssignedInstances;
            meanDistancesToCentroids.put(centroidInstance, meanDistanceToCentroid);
        }
    }
14594
def k_means(
    X,
    n_clusters,
    init="k-means||",
    precompute_distances="auto",
    n_init=1,
    max_iter=300,
    verbose=False,
    tol=1e-4,
    random_state=None,
    copy_x=True,
    n_jobs=-1,
    algorithm="full",
    return_n_iter=False,
    oversampling_factor=2,
    init_max_iter=None,
):
    
    labels, inertia, centers, n_iter = _kmeans_single_lloyd(
        X,
        n_clusters,
        max_iter=max_iter,
        init=init,
        verbose=verbose,
        tol=tol,
        random_state=random_state,
        oversampling_factor=oversampling_factor,
        init_max_iter=init_max_iter,
    )
    if return_n_iter:
        return labels, centers, inertia, n_iter
    else:
        return labels, centers, inertia
1115747
function random$1(data, K) {
                const rand = new Picker$1(data);
                var ans = new Array(K);

                for (var i = 0; i < K; ++i) {
                    ans[i] = rand.pick();
                }
                return ans;
            }
1019058
public void generateRandom( int nbPoints, float minX, float maxX, float minY, float maxY )
	{
		xs = new ArrayList<Float>();
		ys = new ArrayList<Float>();

		for( int i = 0; i < nbPoints; i++ )
		{
			float r = (float) Math.random();
			r = (float) (((int) (r * 100)) / 100.0);
			xs.add( minX + (i * (maxX - minX) / (nbPoints - 1)) );
			ys.add( minY + r * (maxY - minY) );
		}
	}
112257
def fit_cluster(data, assignments, k, P_init, R_init, means):
    
    for c in range(k):
        if data[:,assignments==c].shape[1] == 0:
            _, assignments = kmeans_pp(data, k)
    genes, cells = data.shape
    nb_gene_indices = np.array([True for i in range(genes)])
    for c in range(k):
        c_data = data[:,assignments==c]
        nb_gene_indices = nb_gene_indices & find_nb_genes(c_data)
    for c in range(k):
        c_data = data[:,assignments==c]
        nb_genes = c_data[nb_gene_indices,:]
        poisson_genes = c_data[~nb_gene_indices, :]
        P_init[nb_gene_indices, c], R_init[nb_gene_indices, c] = nb_fit(nb_genes)
        means[~nb_gene_indices, c] = poisson_genes.mean(1)
    return nb_gene_indices
930387
def _centroids(self, verts):
        
        '''
        value = sp.zeros([len(verts), 3])
        for i, i_verts in enumerate(verts):
            value[i] = np.mean(i_verts, axis=0)
        return value
252592
public static double[] computeDxs(List<KmeansPoint> basePoints, List<KmeansPoint> centroids)
    {
        double[] dxs = new double[basePoints.size()];

        double sum = 0.0d;
        double[] nearestCentroid;
        for (int pointIndex = 0; pointIndex < basePoints.size(); pointIndex++)
        {
            // 対象点に対する最近傍中心との距離(dx)を算出し、二乗に比例する重み付き確率分布値を算出
            KmeansPoint targetPoint = basePoints.get(pointIndex);
            KmeansResult kmeanResult = KmeansCalculator.nearestCentroid(targetPoint, centroids);
            nearestCentroid = kmeanResult.getCentroid();
            double dx = MathUtils.distance(targetPoint.getDataPoint(), nearestCentroid);
            double probabilityDist = Math.pow(dx, 2);
            sum += probabilityDist;
            dxs[pointIndex] = sum;
        }

        return dxs;
    }
384844
def fit(self, X):
        
        self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \
              _kmeans(X, self.n_clusters, self.max_iter, self.n_trials, self.tol)
614637
protected static Clustering kMeans(int k, Cluster[] centers, List<? extends Cluster> data) {
		assert (centers.length == k);
		assert (k > 0);

		int dimensions = centers[0].getCenter().length;

		ArrayList<ArrayList<Cluster>> clustering = new ArrayList<ArrayList<Cluster>>();
		for (int i = 0; i < k; i++) {
			clustering.add(new ArrayList<Cluster>());
		}

		while (true) {
			// Assign points to clusters
			for (Cluster point : data) {
				double minDistance = distance(point.getCenter(), centers[0].getCenter());
				int closestCluster = 0;
				for (int i = 1; i < k; i++) {
					double distance = distance(point.getCenter(), centers[i].getCenter());
					if (distance < minDistance) {
						closestCluster = i;
						minDistance = distance;
					}
				}

				clustering.get(closestCluster).add(point);
			}

			// Calculate new centers and clear clustering lists
			SphereCluster[] newCenters = new SphereCluster[centers.length];
			for (int i = 0; i < k; i++) {
				newCenters[i] = calculateCenter(clustering.get(i), dimensions);
				clustering.get(i).clear();
			}
			
			// Convergence check
			boolean converged = true;
			for (int i = 0; i < k; i++) {
				if (!Arrays.equals(centers[i].getCenter(), newCenters[i].getCenter())) {
					converged = false;
					break;
				}
			}
			
			if (converged) {
				break;
			} else {
				centers = newCenters;
			}
		}

		return new Clustering(centers);
	}