1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

  2. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] K-Means Algorithm In Python returning TypeError: 'list' object is not callable

Discussão em 'Python' iniciado por Stack, Setembro 27, 2021.

  1. Stack

    Stack Membro Participativo

    My code is returning a type error when I try to implement a K-means algorithm. I have tried altering the inputs of that line to resolve the error but I am not sure why it is returning the list' object is not callable error.

    def kmeans_cluster(xs, K, steps=1000):
    '''return group assignments for k-means clusters as described in Ch. 4

    K = number of clusters, K >= 1
    xs = input vectors: array of arrays, length(xs) >= k #training set

    returns a list of vectors group_assignments(group_history)
    each vector in the list is the groups assignments at that time step
    group_assignments should be in range(K) for each x in xs'''

    (T, W) = xs.shape
    representatives = np.zeros((K, W)) #z1 to zk
    group_assignments = np.random.randint(0, K, T) #randomly initialized cluster assignments c1...ck
    group_history = [group_assignments]

    # Implement the K-Means Clustering algorithm from chapter 4 here.
    # After each step, append that step's group_assignments to group_history.
    # When the algorithm halts, return group_history and run the following cell to see how the clustering changed with each step

    assign = []
    assign_cluster = []
    for iteration in range(0,steps):
    for i in range(len(xs)):
    distance = {}
    for c in range(K):
    distance[c] = compute_distance(xs,representatives[c])
    assign = assign_cluster(distance,xs[c],representatives)
    group_assignments[assign[0]] = compute_new_cluster(assign[1],representatives[assign[0]])

    if iteration == (steps-1):
    assign_cluster.append(assign)

    return [assign_cluster, K]


    def compute_distance(x1,x2):
    return np.sqrt(np.sum((x1-x2)**2))

    def assign_cluster(distance,x,cluster):
    min_index = min(distance,key=distance.get)
    return [min_index,x,cluster[min_index]]

    def compute_new_cluster(group_assigment,cluster):
    return np.array(group_assigment+cluster)/2


    ---------------------------------------------------------------------------
    TypeError Traceback (most recent call last)
    /tmp/ipykernel_117/2685984261.py in <module>
    3
    4 colormap = ['red', 'green', 'blue']
    ----> 5 groups = kmeans_cluster(clusters, 3)
    6 N = len(groups)
    7 fig, axes = plt.subplots(nrows=N, figsize=(8, 8*N))

    ---> 33 assign = assign_cluster(distance,xs[c],representatives)

    Continue reading...

Compartilhe esta Página