我认为你在第二个 for 循环中的逻辑是关闭的。这是你想要得到的:
import pandas as pd
import numpy as np
import math
from scipy.spatial import distance
from pandas import DataFrame
a = [2, 2, 8, 5, 7, 6, 1, 4]
b = [10, 5, 4, 8, 5, 4, 2, 9]
list1 = []
list2 = []
cluster1 = []
cluster2 = []
df1 = pd.DataFrame({'Column 1': a, 'Column 2': b})
print(df1)
x1 = int(input("Enter seed point X1: "))
y1 = int(input("Enter seed point Y1: "))
x2 = int(input("Enter seed point X2: "))
y2 = int(input("Enter seed point Y2: "))
# calculate Distance
for i, j in zip(a, b):
c1 = round(math.sqrt(math.pow((x1 - i), 2) + math.pow((y1 - j), 2)), 2)
c2 = round(math.sqrt(math.pow((x2 - i), 2) + math.pow((y2 - j), 2)), 2)
list1.append((c1, (i, j)))
list2.append((c2, (i, j)))
df2 = pd.DataFrame({'Distance 1': list1, 'Distance 2': list2})
print(df2)
for i, j in zip(list1, list2):
d0, d1 = i[0], j[0]
if d0 < d1:
cluster1.append(i[1])
else:
cluster2.append(i[1])
print(cluster1)
import matplotlib.pyplot as plt
x1 = [i[0] for i in cluster1]
y1 = [i[1] for i in cluster1]
plt.scatter(x1, y1)
x2 = [i[0] for i in cluster2]
y2 = [i[1] for i in cluster2]
plt.scatter(x2, y2)
plt.show()
如果是这样,这可能不是最优雅的解决方法。
EDIT0:我已包含用于创建原始散点图的代码。
EDIT1:以下是 cmets 中提到的后续问题的代码。这是 k = 2。
import matplotlib.pyplot as plt
import math
a = [2, 2, 8, 5, 7, 6, 1, 4]
b = [10, 5, 4, 8, 5, 4, 2, 9]
x1 = int(input("Enter seed point X1: "))
y1 = int(input("Enter seed point Y1: "))
x2 = int(input("Enter seed point X2: "))
y2 = int(input("Enter seed point Y2: "))
curr_means = [(x1, y1), (x2, y2)]
prev_means = []
while prev_means != curr_means:
prev_means = curr_means
x1 = curr_means[0][0]
y1 = curr_means[0][1]
x2 = curr_means[1][0]
y2 = curr_means[1][1]
list1 = []
list2 = []
cluster1 = set()
cluster2 = set()
for i, j in zip(a, b):
c1 = round(math.sqrt(math.pow((x1 - i), 2) + math.pow((y1 - j), 2)), 2)
c2 = round(math.sqrt(math.pow((x2 - i), 2) + math.pow((y2 - j), 2)), 2)
list1.append((c1, (i, j)))
list2.append((c2, (i, j)))
for i, j in zip(list1, list2):
d0, d1 = i[0], j[0]
if d0 < d1:
cluster1.add(i[1])
else:
cluster2.add(i[1])
print("c1: ", cluster1)
print("c2: ", cluster2)
cluster1_mean_x = sum(x[0] for x in cluster1) / len(cluster1)
cluster1_mean_y = sum(x[1] for x in cluster1) / len(cluster1)
cluster2_mean_x = sum(x[0] for x in cluster2) / len(cluster2)
cluster2_mean_y = sum(x[1] for x in cluster2) / len(cluster2)
curr_means = [(cluster1_mean_x, cluster1_mean_y), (cluster2_mean_x, cluster2_mean_y)]
print('-----------------------------')
print(cluster1)
print(cluster2)
x1 = [i[0] for i in cluster1]
y1 = [i[1] for i in cluster1]
plt.scatter(x1, y1)
x2 = [i[0] for i in cluster2]
y2 = [i[1] for i in cluster2]
plt.scatter(x2, y2)
plt.show()
如上所述,这段代码效率不高,不再干净。对于有关工作代码的问题(例如如何使代码更高效、更干净、更易读),请尝试使用堆栈交换代码审查。