[Python] KMeans Constrained with different cluster size

Discussão em 'Python' iniciado por Stack, Setembro 24, 2024.

  1. Stack

    Stack Membro Participativo

    I have a dataframe with shop coordinates and want to divide them into clusters based on the day a vendor should visit that shop. For example, let's say that there are 180 shops that a vendor should visit. He should visit 30-34 shops from Monday to Friday and, on Saturday, he should visit 60% of the other days.

    How can I do that? Using kmeans-constrained I can only divide them into equally sized clusters. Maybe I need to use some kind of solver or move points between clusters to reach the numbers I want but I don't know how to do that.

    Here is the code that divides them equally:

    # Loop through the vendor clusters
    for vendor in df["vendor"].unique():

    # Number of shops for each vendor
    n_shops = df.loc[df["vendor"] == vendor]["cod_shop"].count()

    # Index
    idx = df.loc[df["vendor"] == vendor].index

    # Number of clusters for days of the week
    num_clusters = 5 # Monday to Friday

    # Average size for the cluster
    avg_size = n_shops / (num_clusters + 0.6)

    # Define limits
    min_shops = round(avg_size - n_shops * pct, 0)
    max_shops = math.ceil(avg_size + n_shops * pct)

    # Model
    kmeans = KMeansConstrained(n_clusters=num_clusters, size_min=min_shops, size_max=max_shops, random_state=42)
    labels = kmeans.fit_predict(df.loc[df["vendor"] == vendor][["latitude", "longitude"]])

    # Add labels to the dataframe
    df.loc[idx, "visit_day"] = labels

    Continue reading...

Compartilhe esta Página