运行K时的AssertionError意味着Main Function

时间:2016-08-01 12:14:38

标签: python-2.7 k-means

运行以下代码时,我在Main Function中收到AssertionError,断言len(args)> 1.有什么想法在代码中出现问题吗?

K-Means聚类实施

import numpy as np
from math import sqrt
import csv
import sys

====

定义一个计算两个数据点之间距离的函数

GAP = 2
MIN_VAL = 1000000

def get_distance(point1, point2):
    dis = sqrt(pow(point1[0] - point2[0],2) + pow(point1[1] - point2[1],2))
    return dis

====

定义从csv

读取数据的函数
def csvreader(data_file):
    sampleData = []
    global Countries
    with open(data_file, 'r') as csvfile:
        read_data = csv.reader(csvfile, delimiter=' ', quotechar='|')
        for row in read_data:
            print ', '.join(row)
        if read_data <> None:
            for f in read_data:
                values = f.split(",")
                if values[0] <> 'Countries':
                    sampleData.append([values[1],values[2]])
        return sampleData

====

编写初始化程序

def cluster_dis(centroid, cluster):
    dis = 0.0
    for point in cluster:
        dis += get_distance(centroid, point)
    return dis

def update_centroids(centroids, cluster_id, cluster):
    x, y = 0.0, 0.0
    length = len(cluster)
    if length == 0:
        return
    for item in cluster:
        x += item[0]
        y += item[1]
    centroids[cluster_id] = (x / length, y / length)

====

使用适当的循环

实现k-means算法
def kmeans(data, k):
    assert k <= len(data)

    seed_ids = np.random.randint(0, len(data), k)
    centroids = [data[idx] for idx in seed_ids]
    clusters = [[] for _ in xrange(k)]
    cluster_idx = [-1] * len(data)

    pre_dis = 0

    while True:
        for point_id, point in enumerate(data):
            min_distance, tmp_id = MIN_VAL, -1
        for seed_id, seed in enumerate(centroids):
            distance = get_distance(seed, point)
        if distance < min_distance:
            min_distance = distance
            tmp_id = seed_id
        if cluster_idx[point_id] != -1:
            dex = clusters[cluster_idx[point_id]].index(point)
        del clusters[cluster_idx[point_id]][dex]
        clusters[tmp_id].append(point)
        cluster_idx[point_id] = tmp_id

        now_dis = 0.0
        for cluster_id, cluster in enumerate(clusters):
            now_dis += cluster_dis(centroids[cluster_id], cluster)
            update_centroids(centroids, cluster_id, cluster)

        delta_dis = now_dis - pre_dis
        pre_dis = now_dis

        if delta_dis < GAP:
            break

    print(centroids)
    print(clusters)

    return centroids, clusters

def main():
    args = sys.argv[1:]
    assert len(args) > 1
    data_file, k = args[0], int(args[1])

    data = csvreader(data_file)
    kmeans(data, k)

if __name__ == '__main__':
    main()

0 个答案:

没有答案