Skip to content

Commit c2c6f7d

Browse files
committed
Поправлена бага
1 parent a277e1a commit c2c6f7d

9 files changed

+21756
-210
lines changed

CLOPE.py

+144-136
Large diffs are not rendered by default.

README.md

+10
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,20 @@
2929
То окажется, что все объекты будут отнесены к самому большому и единственному кластеру. Таким образом, алгоритм оказывается не инвариантным
3030
к размеру кластера.
3131

32+
Рассматривая tf (не является векторным пространством, поэтому вводить расстояние некорректно), можно проводить $H(C)$ интерпретировать, как среднее покоординатное расстояние в манхэтенской метрике до начала координат.
33+
3234

3335
Описание файлов:
3436
testMushrooms.py -- пример работы алгоритма на тестовом множестве https://archive.ics.uci.edu/ml/datasets/mushroom
3537

38+
39+
!!!!!!!!!!!!!!!!!!
40+
Качество кластеризации будем оценивать по обозначенному целевому признаку, а также, согласно критериям информативности:
41+
42+
* AIC
43+
* AMI
44+
!!!!!!!!!!!!!!!!!!
45+
3646
CLOPE.py -- реализация алгоритма
3747

3848
testNoiseVk.py -- тестирование шумов на дополнительную кластеризуемость

data/access.log

+21,495
Large diffs are not rendered by default.

logs_clustering.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import numpy as np
2+
import CLOPE
3+
4+
5+
f = open('data/access.log', 'r')
6+
log = [item for item in f.readlines()]
7+
8+
# 207 уникальных ip
9+
# Все таймзоны одинаковые
10+
# Дни месяцев брать не будем
11+
12+
date = np.array([item.split()[3][1:].split('/') for item in log])
13+
14+
ip = [item.split()[0] + '_0' for item in log]
15+
month = [month + '_1' for month in date[:, 1]]
16+
year = [item.split(':')[0] + '_2' for item in date[:, 2]]
17+
hour = [item.split(':')[1] + '_3' for item in date[:, 2]]
18+
type_of_query = [item.split()[5] + '_4' for item in log]
19+
proto = [item.split()[7] + '_5' for item in log]
20+
code = [item.split()[8] + '_6' for item in log]
21+
browse = [item.split()[11] + '_7' for item in log]
22+
path = [[path for path in item.split()[6].split('/') if len(path) != 0] for item in log]
23+
24+
# trasactions = {i: transact for i, transact in enumerate(np.transpose(np.vstack([ip, month, year, hour, type_of_query, proto, code, browse])))}
25+
trasactions = {i: transact for i, transact in enumerate(np.transpose(path))}
26+
27+
noiseLimit = 0
28+
seed = 41
29+
r = 1.4
30+
clope = CLOPE.CLOPE(print_step=5000, is_save_history=True, random_seed=seed)
31+
clope.init_clusters(trasactions, r, noiseLimit)
32+
clope.print_history_count(r, seed)
33+
34+
while clope.next_step(trasactions, r, noiseLimit) > 0:
35+
clope.print_history_count(r, seed)
36+
37+
38+
39+
count = 0
40+
cl = []
41+
for transact_ind in clope.transaction:
42+
cluster = clope.transaction[transact_ind]
43+
if cluster == 6:
44+
cl.append(trasactions[transact_ind])
45+
count += 1
46+
if count > 20:
47+
break
48+
49+
print(cl)

testMushrooms.py

+38-28
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,55 @@
11
# -*- coding: utf-8 -*-
22
import CLOPE
33
import numpy
4+
import pandas as pd
5+
6+
7+
def get_count_clusters(data, clope):
8+
# Выводим распределение по кластерам съедобных и несъедобных грибов
9+
answ = []
10+
for item in range(0, clope.max_cluster_number):
11+
answ.append({'e': 0, 'p': 0})
12+
for itemTransact in clope.transaction:
13+
cluster = clope.transaction[itemTransact]
14+
if data[itemTransact][0] == 'e':
15+
answ[cluster]['e'] += 1
16+
else:
17+
answ[cluster]['p'] += 1
18+
19+
return pd.DataFrame(answ)
420

521

622
# Прочитываем данные
7-
f = open ('data/agaricus-lepiota.data.txt', 'r')
23+
f = open('data/agaricus-lepiota.data.txt', 'r')
824
# Разделяем данные
925
mushroomsStart = [item.replace('\n', '').split(',') for item in f.readlines()]
10-
numpy.random.seed(42)
26+
seed = 40
27+
numpy.random.seed(seed)
1128
numpy.random.shuffle(mushroomsStart)
1229
mushrooms = {}
1330
for exampleIndex in range(0, len(mushroomsStart)):
14-
for index in range(0, len(mushroomsStart[exampleIndex])):
15-
# Первый столбец -- признак (съедобные (e) или нет(p)). Данный столбец является целым классом. По этому столбцу
16-
# проверяется качество тестирования
17-
if index != 0:
18-
mushrooms[exampleIndex][index - 1] = mushroomsStart[exampleIndex][index] + str(index)
19-
else:
20-
mushrooms[exampleIndex] = [''] * 22
21-
22-
clope = CLOPE.Clope(print_step=1000, is_save_history=True)
31+
for index in range(0, len(mushroomsStart[exampleIndex])):
32+
# Первый столбец -- признак (съедобные (e) или нет(p)). Данный столбец является целым классом. По этому столбцу
33+
# проверяется качество тестирования
34+
if index != 0:
35+
if mushroomsStart[exampleIndex][index] != '?':
36+
mushrooms[exampleIndex][index - 1] = mushroomsStart[exampleIndex][index] + str(index)
37+
else:
38+
print('miss object')
39+
else:
40+
mushrooms[exampleIndex] = [''] * 22
41+
42+
43+
clope = CLOPE.CLOPE(print_step=1000, is_save_history=True, random_seed=seed)
2344
# Начальные данные
24-
iter = 1000
2545
repulsion = 3
26-
isSaveHist = True
2746
noiseLimit = 0
2847
# Инициализируем алгоритм
29-
clope.init(mushrooms, repulsion, noiseLimit)
30-
clope.print_history_count()
48+
clope.init_clusters(mushrooms, repulsion, noiseLimit)
49+
df = get_count_clusters(clope)
50+
clope.print_history_count(repulsion, seed)
3151
# Итерируемся
3252
while clope.next_step(mushrooms, repulsion, noiseLimit) > 0:
33-
clope.print_history_count()
34-
35-
# Выводим распределение по кластерам съедобных и несъедобных грибов
36-
answ = []
37-
for item in range(0, clope.max_cluster_number):
38-
answ.append({'e': 0, 'p': 0})
39-
for itemTransact in clope.transaction:
40-
cluster = clope.transaction[itemTransact]
41-
if mushroomsStart[itemTransact][0] == 'e':
42-
answ[cluster]['e'] += 1
43-
else:
44-
answ[cluster]['p'] += 1
45-
print(answ)
53+
clope.print_history_count(repulsion, seed)
54+
55+
get_count_clusters(mushroomsStart, clope)

testNoiseVk.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@
2727

2828
# Выполнение алгоритма для шумовых кластеров
2929
stopLimit = 0
30-
clopeNoise = CLOPE.Clope()
31-
clopeNoise.init(noiseTransaction, iter, repulsion, isSaveHistory, noiseLimit)
30+
clopeNoise = CLOPE.CLOPE()
31+
clopeNoise.init_clusters(noiseTransaction, iter, repulsion, isSaveHistory, noiseLimit)
3232
print("Инициализация завершена. Число кластеров: ", len(clopeNoise.clusters), ". Число шумовых кластеров при базовой кластеризации: ", len(clope.NoiseClusters))
3333
while countTransfer > stopLimit:
3434
countTransfer = clopeNoise.next_step(noiseTransaction, iter, repulsion, isSaveHistory, noiseLimit)

testUralsib.py

+10-33
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,23 @@
11
# -*- coding: utf-8 -*-
22
import CLOPE
33
import json
4+
import matplotlib.pyplot as plt
45

56
# Прочитываем данные
67
with open('data/clope_features.json', 'r') as f:
78
clients = json.load(f)
89

9-
clope = CLOPE.Clope()
1010
# Начальные данные
11-
iter = 1000
12-
repulsion = 2.3
13-
isSaveHist = True
14-
noiseLimit = 0
15-
max_count_clusters = 40
11+
repulsion = 2
12+
is_save_hist = True
13+
noise_limit = 0
14+
max_count_clusters = None
1615
random_state = 42
17-
# Инициализируем алгоритм
18-
clope.init(clients, iter, repulsion, isSaveHist, noiseLimit, max_count_clusters, random_state)
19-
clope.print_history_count()
20-
# Итерируемся
21-
# while clope.NextStep(clients, iter, 2, isSaveHist, 5000, max_count_clusters, random_state) > 0:
22-
# clope.PrintHistoryCount()
2316

24-
# Выводим распределение по кластерам съедобных и несъедобных грибов
25-
clusters = {}
26-
for itemTransact in clope.transaction:
27-
cl_num = clope.transaction[itemTransact]
28-
if not cl_num in clusters:
29-
clusters[cl_num] = []
30-
clusters[cl_num].append(itemTransact)
31-
32-
with open('data/clusters.json', 'w') as f:
33-
json.dump(clusters, f)
34-
clope.init(clients, iter, 10, isSaveHist, noiseLimit, max_count_clusters, random_state)
17+
clope = CLOPE.CLOPE(print_step=5000, is_save_history=True)
18+
# Инициализируем алгоритм
19+
clope.init_clusters(clients, repulsion, noise_limit)
3520
clope.print_history_count()
3621
# Итерируемся
37-
while clope.next_step(clients, iter, 2, isSaveHist, 5000, max_count_clusters, random_state) > 0:
38-
clope.print_history_count()
39-
40-
# Выводим распределение по кластерам съедобных и несъедобных грибов
41-
answ = []
42-
for item in range(0, len(clope.clusters)):
43-
answ.append({'e': 0, 'p': 0})
44-
for itemTransact in clope.transaction:
45-
classter = clope.transaction[itemTransact]
46-
print(answ)
22+
while clope.next_step(clients, repulsion, 500) > 0:
23+
clope.print_history_count()

testVk.py

+6-9
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44
import CLOPE
55
import pickle
66

7-
8-
97
with open('data/users.pickle', 'rb') as f:
108
dataGroups = pickle.load(f)
119

@@ -21,19 +19,18 @@
2119
dataGroups = copy.deepcopy(dataNew)
2220

2321
# Инициализация параметров алгоритма
24-
repulsion = 1.0015
25-
noiseLimit = -1
26-
isSaveHistory = False
27-
iter = 10000
22+
repulsion = 1.1
23+
noiseLimit = 0
2824
countTransfer = 1000000
2925
stopLimit = 300
3026

3127
# Выполнение алгоритма
32-
clope = CLOPE.Clope()
33-
clope.init(dataGroups, iter, repulsion, isSaveHistory, noiseLimit)
28+
print('Start')
29+
clope = CLOPE.CLOPE()
30+
clope.init_clusters(dataGroups, repulsion, noiseLimit)
3431
print("Инициализация завершена. Число кластеров: ", len(clope.clusters))
3532
while countTransfer > stopLimit:
36-
countTransfer = clope.next_step(dataGroups, iter, repulsion, isSaveHistory, noiseLimit)
33+
countTransfer = clope.next_step(dataGroups, repulsion, noiseLimit)
3734
print("Число перемещений между кластерами", countTransfer, ". Число кластеров: ", len(clope.clusters))
3835

3936
with open('data/CLOPE_users' + '.r=' + str(repulsion) + '.stopLimit=' + str(stopLimit) + '.pickle', 'wb') as f:

testVkDynamicRepulsion.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@
2929
stopLimit = 300
3030

3131
# Выполнение алгоритма
32-
clope = CLOPE.Clope()
33-
clope.init(dataGroups, iter, repulsion, isSaveHistory, noiseLimit)
32+
clope = CLOPE.CLOPE()
33+
clope.init_clusters(dataGroups, iter, repulsion, isSaveHistory, noiseLimit)
3434
print("Инициализация завершена. Число кластеров: ", len(clope.clusters))
3535
for iteration in range(0, 10):
3636
print("Iteration: ", iteration)

0 commit comments

Comments
 (0)