2022-02-07 15:24:23 +01:00
|
|
|
import kmeans as km
|
|
|
|
import utils
|
2022-01-23 10:39:54 +01:00
|
|
|
import json
|
|
|
|
|
|
|
|
METHODS = ['forgy', 'random_partition']
|
2022-01-17 16:21:51 +01:00
|
|
|
|
|
|
|
|
2022-02-07 15:24:23 +01:00
|
|
|
def get_datas_from_json():
|
|
|
|
datas = []
|
|
|
|
with open('data1.json', 'r') as d:
|
|
|
|
datas.append(json.loads(d.read()))
|
|
|
|
with open('data2.json', 'r') as d:
|
|
|
|
datas.append(json.loads(d.read()))
|
|
|
|
return datas
|
2022-01-17 16:21:51 +01:00
|
|
|
|
|
|
|
|
2022-02-07 15:24:23 +01:00
|
|
|
def get_datas_random():
|
|
|
|
datas = []
|
|
|
|
for get_data in [utils.get_data1, utils.get_data2]:
|
|
|
|
datas.append(get_data())
|
|
|
|
return datas
|
2022-01-23 10:39:54 +01:00
|
|
|
|
|
|
|
|
2022-02-07 15:24:23 +01:00
|
|
|
def main():
|
|
|
|
datas = get_datas_from_json()
|
|
|
|
index = 1
|
2022-01-23 10:39:54 +01:00
|
|
|
for data in datas:
|
2022-02-07 15:24:23 +01:00
|
|
|
utils.plot_data(data)
|
2022-01-23 10:39:54 +01:00
|
|
|
for method in METHODS:
|
2022-02-07 15:24:23 +01:00
|
|
|
print(f'Method: {method}')
|
2022-01-23 10:39:54 +01:00
|
|
|
kmeans_data = {}
|
2022-02-07 15:24:23 +01:00
|
|
|
for k in range(2, 21):
|
|
|
|
kmeans_with_err = km.kmeans(data, method, k)
|
|
|
|
km.print_stats(k, [(iterations[-1], err)
|
|
|
|
for iterations, err in kmeans_with_err])
|
2022-01-23 10:39:54 +01:00
|
|
|
min_err = kmeans_with_err[0][1]
|
|
|
|
kmeans = kmeans_with_err[0][0]
|
|
|
|
for temp_kmeans, err in kmeans_with_err:
|
|
|
|
if err < min_err:
|
|
|
|
min_err = err
|
|
|
|
kmeans = temp_kmeans
|
2022-02-07 15:24:23 +01:00
|
|
|
kmeans_data[k] = (kmeans, min_err)
|
|
|
|
km.plot_kmeans(kmeans, k, f'_{method}_{k}_{index}')
|
|
|
|
error_data = [[i, kmeans_data[i][1]] for i in range(2, 21, 2)]
|
|
|
|
utils.plot_error_data(error_data)
|
|
|
|
index += 1
|
2022-01-17 16:21:51 +01:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2022-02-07 15:24:23 +01:00
|
|
|
main()
|