1

我试图让这个算法与 swift 2.1 一起工作:http: //users.eecs.northwestern.edu/~wkliao/Kmeans/

虽然我在这一行得到了错误:

  return map(Zip2Sequence(centroids, clusterSizes)) { Cluster(centroid: $0, size: $1) }

这是完整的功能:

func kmeans<T : ClusteredType>(
        points: [T],
        k: Int,
        seed: UInt32,
        distance: ((T, T) -> Float),
        threshold: Float = 0.0001
    ) -> [Cluster<T>] {

    let n = points.count
    assert(k <= n, "k cannot be larger than the total number of points")

    var centroids = points.randomValues(seed, num: k)
    var memberships = [Int](count: n, repeatedValue: -1)
    var clusterSizes = [Int](count: k, repeatedValue: 0)

    var error: Float = 0
    var previousError: Float = 0

        repeat {
            error = 0
            var newCentroids = [T](count: k, repeatedValue: T.identity)
            var newClusterSizes = [Int](count: k, repeatedValue: 0)

            for i in 0..<n {
                let point = points[i]
                let clusterIndex = findNearestCluster(point, centroids: centroids, k: k, distance: distance)
                if memberships[i] != clusterIndex {
                    error += 1
                    memberships[i] = clusterIndex
                }
                newClusterSizes[clusterIndex]++
                newCentroids[clusterIndex] = newCentroids[clusterIndex] + point
            }
            for i in 0..<k {
                let size = newClusterSizes[i]
                if size > 0 {
                    centroids[i] = newCentroids[i] / size
                }
            }

            clusterSizes = newClusterSizes
            previousError = error
        } while abs(error - previousError) > threshold

        return map(Zip2Sequence(centroids, clusterSizes)) { Cluster(centroid: $0, size: $1) }
}

我将如何更改它以消除此错误?

4

1 回答 1

2

据我了解,您正在尝试执行以下操作:

return (0..<k).map { Cluster(centroid: centroids[$0], size: clusterSizes[$0]) }

SwiftZip2Sequence<Sequence1, Sequence2>文档中:

由两个底层序列构成的对序列,其中i第 th 对的i元素是每个底层序列的第 th 个元素。

Zip2Sequence<[T], [Int]>生成器的元素是(T, Int)元组。您可以通过索引访问此元组的各个元素。

因此,以下代码应该适合您:

return Zip2Sequence(centroids, clusterSizes).map { Cluster(centroid: $0.0, size: $0.1) }
于 2016-01-16T03:17:02.300 回答