다음 데이터 세트가 있습니다.
node bc cluster
1 russian 0.457039 1
48 man 0.286875 1
155 woman 0.129939 0
3 bit 0.092721 0
5 write 0.065424 0
98 age 0.064347 0
97 escap 0.062675 0
74 game 0.062606 0
그런 다음 kMeans 클러스터링을 bc
값 별로 수행 하여 노드를 두 개의 다른 그룹으로 분리합니다. 바로 지금 아래 코드를 사용하여 위의 결과를 얻습니다 (클러스터링 결과가 cluster
열에 있음).
bc_df = pd.DataFrame({"node": bc_nodes, "bc": bc_values})
bc_df = bc_df.sort_values("bc", ascending=False)
km = KMeans(n_clusters=2).fit(bc_df[['bc']])
bc_df.loc[:,'cluster'] = km.labels_
print(bc_df.head(8))
꽤 좋지만 약간 다르게 작동하고 첫 번째 클러스터에서 처음 4 개 노드를 선택한 다음 두 번째 클러스터에서 다른 노드를 선택하는 것이 서로 더 비슷하기 때문입니다.
kMeans에 약간의 조정을 할 수 있습니까? 아니면 sklearn
그렇게 할 수있는 다른 알고리즘을 알고 계십니까?
원하는 것은 1 차원 데이터에 대한 클러스터링입니다. 이 문제를 해결하는 한 가지 방법은 Jenks Natural Breaks를 사용하는 것입니다 (Google에서 설명을 얻음).
나는이 함수를 작성하지 않았습니다 (많은 신용이 여기에 그의 솔루션과 함께 @Frank로 이동합니다 )
데이터 프레임이 주어지면 :
import pandas as pd
df = pd.DataFrame([
['russian', 0.457039],
['man', 0.286875],
['woman', 0.129939],
['bit', 0.092721],
['write', 0.065424],
['age', 0.064347],
['escap', 0.062675],
['game', 0.062606]], columns = ['node','bc'])
Jenks Natural Break 기능을 사용한 코드 :
def get_jenks_breaks(data_list, number_class):
data_list.sort()
mat1 = []
for i in range(len(data_list) + 1):
temp = []
for j in range(number_class + 1):
temp.append(0)
mat1.append(temp)
mat2 = []
for i in range(len(data_list) + 1):
temp = []
for j in range(number_class + 1):
temp.append(0)
mat2.append(temp)
for i in range(1, number_class + 1):
mat1[1][i] = 1
mat2[1][i] = 0
for j in range(2, len(data_list) + 1):
mat2[j][i] = float('inf')
v = 0.0
for l in range(2, len(data_list) + 1):
s1 = 0.0
s2 = 0.0
w = 0.0
for m in range(1, l + 1):
i3 = l - m + 1
val = float(data_list[i3 - 1])
s2 += val * val
s1 += val
w += 1
v = s2 - (s1 * s1) / w
i4 = i3 - 1
if i4 != 0:
for j in range(2, number_class + 1):
if mat2[l][j] >= (v + mat2[i4][j - 1]):
mat1[l][j] = i3
mat2[l][j] = v + mat2[i4][j - 1]
mat1[l][1] = 1
mat2[l][1] = v
k = len(data_list)
kclass = []
for i in range(number_class + 1):
kclass.append(min(data_list))
kclass[number_class] = float(data_list[len(data_list) - 1])
count_num = number_class
while count_num >= 2: # print "rank = " + str(mat1[k][count_num])
idx = int((mat1[k][count_num]) - 2)
# print "val = " + str(data_list[idx])
kclass[count_num - 1] = data_list[idx]
k = int((mat1[k][count_num] - 1))
count_num -= 1
return kclass
# Get values to find the natural breaks
x = list(df['bc'])
# Calculate the break values.
# I want 2 groups, so parameter is 2.
# If you print (get_jenks_breaks(x, 2)), it will give you 3 values: [min, break1, max]
# Obviously if you want more groups, you'll need to adjust this and also adjust the assign_cluster function below.
breaking_point = get_jenks_breaks(x, 2)[1]
# Creating group for the bc column
def assign_cluster(bc):
if bc < breaking_point:
return 0
else:
return 1
# Apply `assign_cluster` to `df['bc']`
df['cluster'] = df['bc'].apply(assign_cluster)
산출:
print (df)
node bc cluster
0 russian 0.457039 1
1 man 0.286875 1
2 woman 0.129939 1
3 bit 0.092721 0
4 write 0.065424 0
5 age 0.064347 0
6 escap 0.062675 0
7 game 0.062606 0
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다