Create clasterization diagram.

This commit is contained in:
ElEgEv 2023-12-06 22:20:51 +04:00
parent 440a5e42a5
commit 9bcddc560e
6 changed files with 148 additions and 8 deletions

View File

@ -0,0 +1,81 @@
import copy
import random
from matplotlib import pyplot as plt
class clasterization:
def __init__(self, arr, k):
print(f"Количество центров: {k}")
print(f"Массив?: {arr}")
self.arr = arr
self.k = k
self.n = len(self.arr)
self.dim = len(self.arr[0])
def data_distr(self, cluster):
cluster_content = [[] for i in range(self.k)]
for i in range(self.n):
min_dist = float('inf')
sit_clust = -1
for j in range(self.k):
dist = 0
for q in range(self.dim):
dist += (self.arr[i][q] - cluster[j][q])**2
dist = dist**(1/2)
if dist < min_dist:
min_dist = dist
sit_clust = j
cluster_content[sit_clust].append(self.arr[i])
return cluster_content
def cluster_update(self, cluster, cluster_content):
k = len(cluster)
for i in range(self.k):
for q in range(self.dim):
updated_param = 0
for j in range(len(cluster_content[i])):
updated_param += cluster_content[i][j][q]
if len(cluster_content[i]) != 0:
updated_param = updated_param / len(cluster_content[i])
cluster[i][q] = updated_param
return cluster
def visualisation_2d(self, cluster_content):
k = len(cluster_content)
plt.grid()
plt.xlabel("Площадь магазина (Store_Area)")
plt.ylabel("Объём продаж (Store_Sales)")
for i in range(k):
x_coordinates = []
y_coordinates = []
for q in range(len(cluster_content[i])):
x_coordinates.append(cluster_content[i][q][0])
y_coordinates.append(cluster_content[i][q][1])
plt.scatter(x_coordinates, y_coordinates)
def clast(self):
cluster = [[0 for i in range(self.dim)] for q in range(self.k)]
cluster_content = [[] for i in range(self.k)]
for i in range(self.dim):
for q in range(self.k):
cluster[q][i] = random.randint(0, 2)
cluster_content = self.data_distr(cluster)
prev_clust = copy.deepcopy(cluster)
while 1:
cluster = self.cluster_update(cluster, cluster_content)
cluster_content = self.data_distr(cluster)
if cluster == prev_clust:
break
prev_clust = copy.deepcopy(cluster)
self.visualisation_2d(cluster_content)

View File

@ -0,0 +1,25 @@
import os
from matplotlib import pyplot as plt
import pandas as pd
from LabWork01.LabWork7.Clastarization import clasterization
# генерация изображения
def CreateClasterizationJpg(data: pd.DataFrame):
# для сохранения диаграммы в конкретной папке
script_dir = os.path.dirname(__file__)
results_dir = os.path.join(script_dir, '../static/')
if not os.path.isdir(results_dir):
os.makedirs(results_dir)
plt.figure(figsize=(20, 6))
clast = clasterization(data.iloc[:, [1, 4]].to_numpy(), 3)
clast.clast()
plt.savefig(results_dir + 'DiagramClasterization.jpg')
plt.clf()
return True

View File

@ -15,6 +15,7 @@ from LabWork01.LabWork3.DeletePng import deleteAllPng
from LabWork01.LabWork4.SiteSearch import SiteSearch
from LabWork01.LabWork5.Сreate_plot import create_plot_jpg
from LabWork01.LabWork6.Tree import getStringTree
from LabWork01.LabWork7.CreateClasterizationJpg import CreateClasterizationJpg
app = Flask(__name__)
@ -190,13 +191,6 @@ def get_page_showFindURL():
# 5-я лабораторная
@app.route('/createPlotImage', methods=['GET', 'POST'])
def get_plot_image():
# 99%
# main_df = listShops.loc[listShops['Store_ID'] <= listShops.shape[0]*0.9]
# 1%
# support_df = listShops.loc[listShops['Store_ID'] > listShops.shape[0]*0.9]
messages = create_plot_jpg(listShops, "myPlot")
myPlotJpg = ['myPlot.jpg']
@ -219,6 +213,15 @@ def get_data_Tree():
return render_template('tree_page.html', DataTree=DataTree)
@app.route('/createClasterization', methods=['GET', 'POST'])
def clast():
CreateClasterizationJpg(listShops)
clasterizationJpg = ['DiagramClasterization.jpg']
return render_template('clasterization.html', clasterizationJpg=clasterizationJpg)
if __name__=="__main__":
app.run(debug=True)

View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="container">
<form action="/" method="get">
<div class="mb-5 mt-3">
<label class="form-label">Диаграмма кластеризации</label>
<div class="row">
<div class="col">
<input type=submit value='Главная'>
</div>
</div>
</div>
</form>
<div class>
{% for image_name in clasterizationJpg %}
<img src="{{ url_for('static', filename=image_name) }}" alt="{{ image_name }}">
{% endfor %}
</div>
</div>
</body>
</html>

View File

@ -36,6 +36,11 @@
<button type="submit" class="btn btn-primary mb-3">Построить дерево</button>
</div>
</form>
<form action="/createClasterization" method="get">
<div class="mb-3">
<button type="submit" class="btn btn-primary mb-3">Диаграмма кластеризации</button>
</div>
</form>
</div>
<div>
<table>

View File

@ -22,7 +22,7 @@
</div>
</div>
</form>
<div class="">
<div>
{% for item in DataTree %}
{% if item.count("\t") == 1 %}
<p style="margin-left: 50px;"> {{ item }}</p>