指定した点を用いて学習モデルを生成する。<br>

@param pointList 学習モデルのベース点情報
@param clusterNum 分類クラスタ数
@param maxIteration 最大イテレーション回数
@param convergenceThres 収束したと判断する閾値
@return 生成された学習モデル
546076
public static KmeansDataSet createDataModel(List<KmeansPoint> pointList, int clusterNum,
            int maxIteration, double convergenceThres)
    {
        // クラスタ数よりもデータ数が少ない場合、結果はnullとして返す。
        if (pointList.size() < clusterNum)
        {
            return null;
        }

        // 初回の中心点リストを生成する。
        List<KmeansPoint> centroids = createInitialCentroids(pointList, clusterNum);
        long[] clusteredNum = new long[clusterNum];

        // イテレーションを最大回数実行し、収束を試みる。
        for (int exeIndex = 0; exeIndex < maxIteration; exeIndex++)
        {
            Map<Integer, List<KmeansPoint>> assignments = Maps.newHashMap();
            for (int centroidIndex = 0; centroidIndex < clusterNum; centroidIndex++)
            {
                assignments.put(centroidIndex, Lists.<KmeansPoint> newArrayList());
            }

            for (KmeansPoint targetPoint : pointList)
            {
                KmeansResult result = nearestCentroid(targetPoint, centroids);
                assignments.get(result.getCentroidIndex()).add(targetPoint);
            }

            List<KmeansPoint> newCentroids = Lists.newArrayList();
            for (Map.Entry<Integer, List<KmeansPoint>> entry : assignments.entrySet())
            {
                if (entry.getValue().isEmpty())
                {
                    newCentroids.add(centroids.get(entry.getKey()));
                }
                else
                {
                    newCentroids.add(calculateCentroid(entry.getValue()));
                }

                clusteredNum[entry.getKey()] = entry.getValue().size();
            }

            boolean isConvergenced = isConvergenced(centroids, newCentroids, convergenceThres);
            centroids = newCentroids;

            if (isConvergenced == true)
            {

                break;
            }
        }

        double[][] centroidPoints = new double[clusterNum][];

        for (int centroidIndex = 0; centroidIndex < clusterNum; centroidIndex++)
        {
            centroidPoints[centroidIndex] = centroids.get(centroidIndex).getDataPoint();
        }

        KmeansDataSet createdModel = new KmeansDataSet();
        createdModel.setCentroids(centroidPoints);
        createdModel.setClusteredNum(clusteredNum);
        return createdModel;
    }
268166
public void setImplicitConvergenceCriterion(String aggregatorName, ConvergenceCriterion<?> convCriterion) {
		try {
			InstantiationUtil.writeObjectToConfig(convCriterion, this.config, ITERATION_IMPLICIT_CONVERGENCE_CRITERION);
		} catch (IOException e) {
			throw new RuntimeException("Error while writing the implicit convergence criterion object to the task configuration.");
		}
		this.config.setString(ITERATION_IMPLICIT_CONVERGENCE_CRITERION_AGG_NAME, aggregatorName);
	}
219242
@Override
  public void computeDensityEstimator(List<S> solutionList) {
    int size = solutionList.size();

    if (size <= solutionList.get(0).getNumberOfObjectives()) {
      for (int x = 0; x < size; x++) {
        solutionList.get(x).setAttribute(getAttributeID(), Double.POSITIVE_INFINITY);
      }
      return;
    }

    // Use a new SolutionSet to avoid altering the original solutionSet
    List<S> front = new ArrayList<>(size);
    for (S solution : solutionList) {
      front.add(solution);
    }

    for (int i = 0; i < size; i++) {
      front.get(i).setAttribute(getAttributeID(), 0.0);
    }

    int numberOfObjectives = solutionList.get(0).getNumberOfObjectives();

    double objetiveMaxn[] = new double[numberOfObjectives];
    double objetiveMinn[] = new double[numberOfObjectives];
    double distan;

    for (int i = 0; i < numberOfObjectives; i++) {
      // Sort the population by Obj n
      Collections.sort(front, new ObjectiveComparator<S>(i));
      objetiveMinn[i] = front.get(0).getObjective(i);
      objetiveMaxn[i] = front.get(front.size() - 1).getObjective(i);

      // Set de crowding distance Los extremos si infinitos
      front.get(0).setAttribute(getAttributeID(), Double.POSITIVE_INFINITY);
      front.get(size - 1).setAttribute(getAttributeID(), Double.POSITIVE_INFINITY);
    }
    double[][] distance =
        SolutionListUtils.distanceMatrix_normalize(front, objetiveMaxn, objetiveMinn);

    double dminn, dmaxx;
    dminn = Double.MAX_VALUE;
    dmaxx = 0.0;
    for (int i = 0; i < distance.length; i++)
      for (int j = 0; j < distance.length; j++) {
        if (i != j) {
          if (distance[i][j] < dminn) {
            dminn = distance[i][j];
          }
          if (distance[i][j] > dmaxx) {
            dmaxx = distance[i][j];
          }
        }
      }

    for (int i = 0; i < front.size(); i++) {
      double temp = 0.0;
      for (int j = 0; j < distance.length; j++) {
        if (i != j) {
          temp += Math.pow(distance[i][j] - (dmaxx - dminn), 2);
        }
      }
      temp /= distance.length - 1;
      temp = Math.sqrt(temp);
      temp *= -1;
      temp += (double) front.get(i).getAttribute(getAttributeID());
      // if((double) front.get(i).getAttribute(getAttributeID())!=Double.POSITIVE_INFINITY)
      front.get(i).setAttribute(getAttributeID(), temp);
    }

    // int k = numberOfObjectives la solucion 0 es ella misma
    for (int i = 0; i < distance.length; i++) {
      Arrays.sort(distance[i]);
      double kDistance = 0.0;
      for (int k = numberOfObjectives; k > 0; k--) {
        // kDistance += (dmaxx-dminn) / (distance[i][k]);//me gusta mas este
        // kDistance += (dmaxx-dminn) / (distance[i][k]+dminn);//original
        kDistance += (dmaxx - dminn) / distance[i][k];
      }
      double temp = (double) front.get(i).getAttribute(getAttributeID());
      // if(temp!=Double.POSITIVE_INFINITY)
      // kDistance=kDistance/numberOfObjectives-1;
      temp -= kDistance;
      front.get(i).setAttribute(getAttributeID(), temp);
    }
  }
154308
public List<Set<K>> kmeans(int nclusters)
    {
        Cluster<K> cluster = new Cluster<K>();
        for (Document<K> document : documents_.values())
        {
            cluster.add_document(document);
        }
        cluster.section(nclusters);
        refine_clusters(cluster.sectioned_clusters());
        List<Cluster<K>> clusters_ = new ArrayList<Cluster<K>>(nclusters);
        for (Cluster<K> s : cluster.sectioned_clusters())
        {
            s.refresh();
            clusters_.add(s);
        }
        return toResult(clusters_);
    }
96025
@Override
	public void resetLearningImpl() {
		this.numClusters = this.numClustersOption.getValue();
		this.numDimensions = this.numDimensionsOption.getValue();
		this.maxNumClusterFeatures = this.maxNumClusterFeaturesOption.getValue();
		this.numProjections = this.numProjectionsOption.getValue();

		this.bufferPhase = true;
		this.buffer = new ArrayList<double[]>(
				this.maxNumClusterFeaturesOption.getValue() + 1);
		this.minDistance = Double.POSITIVE_INFINITY;
		this.pairwiseDifferent = 0;

		int hashSize = (int) Math.ceil(Math.log(
				5 * this.maxNumClusterFeaturesOption.getValue()) / Math.log(2));
		this.root = new ClusteringTreeHeadNode(null, new ClusteringFeature(
				new double[0], 1), this.numDimensionsOption.getValue(),
				this.numProjectionsOption.getValue(), Math.min(hashSize, 30),
				this.clustererRandom);
		this.rootCount = 0;
	}
1194574
public List<Cluster> cluster(final Collection<Point2D> points) {
    	final List<Cluster> clusters = new ArrayList<Cluster>();
        final Map<Point2D, PointStatus> visited = new HashMap<Point2D, DBScan.PointStatus>();

        KDTree<Point2D> tree = new KDTree<Point2D>(2);
        
        // Populate the kdTree
        for (final Point2D point : points) {
        	double[] key = {point.x, point.y};
        	tree.insert(key, point);
        }
                
        for (final Point2D point : points) {
            if (visited.get(point) != null) {
                continue;
            }
            final List<Point2D> neighbors = getNeighbors(point, tree);
            if (neighbors.size() >= minPoints) {
                // DBSCAN does not care about center points
                final Cluster cluster = new Cluster(clusters.size());
                clusters.add(expandCluster(cluster, point, neighbors, tree, visited));
            } else {
                visited.put(point, PointStatus.NOISE);
            }
        }

        for (Cluster cluster : clusters) {
        	cluster.calculateCentroid();
        }
        
        return clusters;
    }
1282509
void getClusterXY(int cluster, Point2D ptOut) {
		int vindex = getClusterVertexIndex(cluster);
		m_shape.getXYWithIndex(vindex, ptOut);
	}
835829
public static Assignments cluster(Matrix matrix,
                                      int numClusters,
                                      int numRepetitions,
                                      KMeansSeed seedType,
                                      CriterionFunction criterion) {
        int[] bestAssignment = null;
        double bestScore = (criterion.isMaximize()) ? 0 : Double.MAX_VALUE;
        for (int i = 0; i < numRepetitions; ++i) {
            clusterIteration(matrix, numClusters, seedType, criterion);
            if (criterion.isMaximize()) {
                if (criterion.score() > bestScore) {
                    bestScore = criterion.score();
                    bestAssignment = criterion.assignments();
                }
            } else {
                if (criterion.score() < bestScore) {
                    bestScore = criterion.score();
                    bestAssignment = criterion.assignments();
                }
            }
        }

        // Convert the array of assignments to an Assignments object.
        Assignment[] assignments = new Assignment[matrix.rows()];
        for (int i = 0; i < bestAssignment.length; ++i)
            assignments[i] = new HardAssignment(bestAssignment[i]);

        return new Assignments(numClusters, assignments, matrix);
    }
1310875
public List<Set<K>> repeatedBisection(int nclusters, double limit_eval)
    {
        Cluster<K> cluster = new Cluster<K>();
        List<Cluster<K>> clusters_ = new ArrayList<Cluster<K>>(nclusters > 0 ? nclusters : 16);
        for (Document<K> document : documents_.values())
        {
            cluster.add_document(document);
        }

        PriorityQueue<Cluster<K>> que = new PriorityQueue<Cluster<K>>();
        cluster.section(2);
        refine_clusters(cluster.sectioned_clusters());
        cluster.set_sectioned_gain();
        cluster.composite_vector().clear();
        que.add(cluster);

        while (!que.isEmpty())
        {
            if (nclusters > 0 && que.size() >= nclusters)
                break;
            cluster = que.peek();
            if (cluster.sectioned_clusters().size() < 1)
                break;
            if (limit_eval > 0 && cluster.sectioned_gain() < limit_eval)
                break;
            que.poll();
            List<Cluster<K>> sectioned = cluster.sectioned_clusters();

            for (Cluster<K> c : sectioned)
            {
                c.section(2);
                refine_clusters(c.sectioned_clusters());
                c.set_sectioned_gain();
                if (c.sectioned_gain() < limit_eval)
                {
                    for (Cluster<K> sub : c.sectioned_clusters())
                    {
                        sub.clear();
                    }
                }
                c.composite_vector().clear();
                que.add(c);
            }
        }
        while (!que.isEmpty())
        {
            clusters_.add(0, que.poll());
        }
        return toResult(clusters_);
    }
1283321
private static <S extends Solution<?>> double[][] getExtremePoints(List<S> solutionsList) {
    // One extreme point for each objective
    double[][] extremePoints = new double[solutionsList.get(0).getNumberOfObjectives()][];

    for (int i = 0; i < extremePoints.length; i++) {
      S extreme = Collections.min(solutionsList, new AchievementScalarizationComparator<S>(i));
      extremePoints[i] = new double[extreme.getNumberOfObjectives()];
      for (int j = 0; j < extremePoints.length; j++) {
        extremePoints[i][j] = extreme.getObjective(j);
      }
    }

    return extremePoints;
  }
643591
public void setFromPoints(Point2D[] points) {
		if (points == null || points.length == 0) {
			setEmpty();
			return;
		}

		Point2D pt = points[0];
		setCoords(pt.x, pt.y);
		for (int i = 1; i < points.length; i++) {
			Point2D pt2d = points[i];
			mergeNE(pt2d.x, pt2d.y);
		}
	}
1264326
def _centroids(n_clusters: int, points: List[List[float]]) -> List[List[float]]:
    

    k_means = KMeans(n_clusters=n_clusters)
    k_means.fit(points)

    closest, _ = pairwise_distances_argmin_min(k_means.cluster_centers_, points)

    return list(map(list, np.array(points)[closest.tolist()]))
447433
public Cluster toCluster() {
		double[] output = new double[this.sumPoints.length];
		System.arraycopy(this.sumPoints, 0, output, 0, this.sumPoints.length);
		for (int i = 0; i < output.length; i++) {
			output[i] /= this.numPoints;
		}
		return new SphereCluster(output, getThreshold(), this.numPoints);
	}
717102
protected void matchPointsToClusters(List<double[]> points) {
		sumDistance = 0;
		for (int i = 0; i < points.size(); i++) {
			double[]p = points.get(i);

			// find the cluster which is closest to the point
			int bestCluster = findBestMatch(p);

			// sum up all the points which are members of this cluster
			double[] c = workClusters.get(bestCluster);
			for (int j = 0; j < c.length; j++) {
				c[j] += p[j];
			}
			memberCount.data[bestCluster]++;
			labels.data[i] = bestCluster;
			sumDistance += bestDistance;
		}
	}
756883
private void setInitialPartitions(double[][] pointArray, int k) {
		if (pointArray.length < k) {
			System.err.println("cannot cluster less than k points into k clusters...");
			System.exit(0);
		}
		
		// select randomly k initial means
		// TODO: choose more stable initialization (comment: this is run several times (with different random seeds), i.e. the worst case should not occur)
        Random random = new Random(randomSeed);
		TreeSet<Integer> usedPoints = new TreeSet<Integer>();
		int nextIndex;
		for (int i = 0; i < k; i++) {
			nextIndex = ((Double)(Math.floor(random.nextDouble() * n))).intValue();
			if (usedPoints.contains(nextIndex)) {
				i--;
				continue;
			} else {
				for (int d = 0; d < dim; d++) {
					clusterMeans[i][d] = pointArray[nextIndex][d];
				}
			}
		}
		
		// set pCgivenX=1 for the closest C for each point
		int minDistIndex = 0;
		double minDist, currentDist;
		for (int x = 0; x < pointArray.length; x++) {
			minDist = Double.MAX_VALUE;
			for (int i = 0; i < k; i++) {
				currentDist = euclideanDistance(clusterMeans[i], pointArray[x]);
				if (currentDist < minDist) {
					minDist = currentDist;
					minDistIndex = i;
				}
			}
			pCgivenX[minDistIndex][x] = 1.0;
		}
	}
1200842
public <E extends Edge> MultiMap<Integer,Integer> cluster(
                      final Graph<E> graph, int numClusters, Properties props) {
        return singleLink(graph, numClusters);
        // throw new Error();
    }
521560
public static ClusterSetInfo classifyPoints(final ClusterSet clusterSet, List<Point> points,
                    ExecutorService executorService) {
        final ClusterSetInfo clusterSetInfo = ClusterSetInfo.initialize(clusterSet, true);

        List<Runnable> tasks = new ArrayList<>();
        for (final Point point : points) {
            //tasks.add(new Runnable() {
              //  public void run() {
                    try {
                        PointClassification result = classifyPoint(clusterSet, point);
                        if (result.isNewLocation())
                            clusterSetInfo.getPointLocationChange().incrementAndGet();
                        clusterSetInfo.getClusterInfo(result.getCluster().getId()).getPointDistancesFromCenter()
                                        .put(point.getId(), result.getDistanceFromCenter());
                    } catch (Throwable t) {
                        log.warn("Error classifying point", t);
                    }
            //    }
            }

        //MultiThreadUtils.parallelTasks(tasks, executorService);
        return clusterSetInfo;
    }