Dunn index and inertia in kmeans algorithm

I have code which runs a KMeans algorithm on some data but i need it to now calculate the Dunn index and inertia for it but since the restrictions to this program is numpy, matplotlib and csv, no video online shows how to calculate the Dunn index with just these couple libraries, i am not very fond of math so implementing the actual math into the code is just too hard for me…

I have searched online for how to calculate dunn index and inertia in python with the limitations of numpy but everything used another library.

Here is the code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import numpy as np
import matplotlib.pyplot as plt
import csv
def load_data(file_path):
data = []
with open(file_path, 'r') as csvfile:
csvreader = csv.reader(csvfile)
next(csvreader)
for row in csvreader:
data.append([float(row[0]), float(row[1])])
return np.array(data)
def calculate_distances(data, centers):
data_with_distances = data.copy()
num_centers = centers.shape[0]
for i in range(num_centers):
distances = np.sqrt(((data - centers[i]) ** 2).sum(axis=1))
data_with_distances = np.column_stack((data_with_distances, distances))
return data_with_distances
def get_clusters(data_with_distances):
num_clusters = data_with_distances.shape[1] - 2
cluster_masks = []
for i in range(num_clusters):
mask = data_with_distances[:, i+2] == np.min(data_with_distances[:, 2:num_clusters+2], axis=1)
cluster_masks.append(mask)
clusters = [data_with_distances[mask, :] for mask in cluster_masks]
return clusters
def calculate_centers(clusters):
centers = np.array([cluster.mean(axis=0)[:2] for cluster in clusters])
return centers
def plot_clusters(clusters, centers):
colors = ['blue', 'red', 'green']
for i, cluster in enumerate(clusters):
plt.scatter(cluster[:, 0], cluster[:, 1], color=colors[i])
for center in centers:
plt.scatter(center[0], center[1], color='purple', marker='*', s=150)
plt.xlabel('Household Total Assets')
plt.ylabel('Annual Household Income')
plt.title('K-means Clustering of Household Data')
plt.show()
def run(data, num_clusters, max_iterations=100):
current_centers = np.random.permutation(data)[:num_clusters]
for iteration in range(max_iterations):
data_with_distances = calculate_distances(data, current_centers)
clusters = get_clusters(data_with_distances)
current_centers = calculate_centers(clusters)
plot_clusters(clusters, current_centers)
def main(file_path):
data = load_data(file_path)
for num_clusters in range(2, 11):
run(data, num_clusters)
file_path = 'assessment2dmv.csv'
num_clusters = 3
main(file_path)
</code>
<code>import numpy as np import matplotlib.pyplot as plt import csv def load_data(file_path): data = [] with open(file_path, 'r') as csvfile: csvreader = csv.reader(csvfile) next(csvreader) for row in csvreader: data.append([float(row[0]), float(row[1])]) return np.array(data) def calculate_distances(data, centers): data_with_distances = data.copy() num_centers = centers.shape[0] for i in range(num_centers): distances = np.sqrt(((data - centers[i]) ** 2).sum(axis=1)) data_with_distances = np.column_stack((data_with_distances, distances)) return data_with_distances def get_clusters(data_with_distances): num_clusters = data_with_distances.shape[1] - 2 cluster_masks = [] for i in range(num_clusters): mask = data_with_distances[:, i+2] == np.min(data_with_distances[:, 2:num_clusters+2], axis=1) cluster_masks.append(mask) clusters = [data_with_distances[mask, :] for mask in cluster_masks] return clusters def calculate_centers(clusters): centers = np.array([cluster.mean(axis=0)[:2] for cluster in clusters]) return centers def plot_clusters(clusters, centers): colors = ['blue', 'red', 'green'] for i, cluster in enumerate(clusters): plt.scatter(cluster[:, 0], cluster[:, 1], color=colors[i]) for center in centers: plt.scatter(center[0], center[1], color='purple', marker='*', s=150) plt.xlabel('Household Total Assets') plt.ylabel('Annual Household Income') plt.title('K-means Clustering of Household Data') plt.show() def run(data, num_clusters, max_iterations=100): current_centers = np.random.permutation(data)[:num_clusters] for iteration in range(max_iterations): data_with_distances = calculate_distances(data, current_centers) clusters = get_clusters(data_with_distances) current_centers = calculate_centers(clusters) plot_clusters(clusters, current_centers) def main(file_path): data = load_data(file_path) for num_clusters in range(2, 11): run(data, num_clusters) file_path = 'assessment2dmv.csv' num_clusters = 3 main(file_path) </code>
import numpy as np
import matplotlib.pyplot as plt
import csv

def load_data(file_path):
    data = []
    with open(file_path, 'r') as csvfile:
        csvreader = csv.reader(csvfile)
        next(csvreader)
        for row in csvreader:
            data.append([float(row[0]), float(row[1])])
    return np.array(data)

def calculate_distances(data, centers):
    data_with_distances = data.copy()
    num_centers = centers.shape[0]
    
    for i in range(num_centers):
        distances = np.sqrt(((data - centers[i]) ** 2).sum(axis=1))
        data_with_distances = np.column_stack((data_with_distances, distances))
    
    return data_with_distances

def get_clusters(data_with_distances):
    num_clusters = data_with_distances.shape[1] - 2 
    cluster_masks = []
    for i in range(num_clusters):
        mask = data_with_distances[:, i+2] == np.min(data_with_distances[:, 2:num_clusters+2], axis=1)
        cluster_masks.append(mask)
    
    clusters = [data_with_distances[mask, :] for mask in cluster_masks]
    return clusters

def calculate_centers(clusters):
    centers = np.array([cluster.mean(axis=0)[:2] for cluster in clusters])
    return centers

def plot_clusters(clusters, centers):
    colors = ['blue', 'red', 'green']
    for i, cluster in enumerate(clusters):
        plt.scatter(cluster[:, 0], cluster[:, 1], color=colors[i])
    for center in centers:
        plt.scatter(center[0], center[1], color='purple', marker='*', s=150)
    plt.xlabel('Household Total Assets')
    plt.ylabel('Annual Household Income')
    plt.title('K-means Clustering of Household Data')
    plt.show()

def run(data, num_clusters, max_iterations=100):
    current_centers = np.random.permutation(data)[:num_clusters]
    
    for iteration in range(max_iterations):
        data_with_distances = calculate_distances(data, current_centers)
        clusters = get_clusters(data_with_distances)
        current_centers = calculate_centers(clusters)

    plot_clusters(clusters, current_centers)
    
def main(file_path):
    data = load_data(file_path)
    for num_clusters in range(2, 11):
        run(data, num_clusters)

file_path = 'assessment2dmv.csv'
num_clusters = 3
main(file_path)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật