k-1 군집 중심 정의 — SKlearn KMeans

Nov 19 2020

부분적으로 레이블이 지정된 데이터 세트의 이진 분류를 수행하고 있습니다. 1은 신뢰할 수 있지만 0은 아닙니다.

sklearn KMeans 문서에서 :

init : {‘k-means++’, ‘random’ or an ndarray}
Method for initialization, defaults to ‘k-means++’:   
If an ndarray is passed, it should be of shape (n_clusters, n_features) and gives the initial centers.

ndarray를 전달하고 싶지만 신뢰할 수있는 중심이 2 개가 아니라 1 개뿐입니다.

K-1 중심과 K 사이의 엔트로피를 최대화하는 방법이 있습니까? 또는 K-1 중심을 수동으로 초기화하고 나머지에 K ++를 사용하는 방법이 있습니까?

================================================ =====

관련 질문 :

이것은 n-1 피처로 K 중심을 정의하려고합니다. (n 개의 특징으로 k-1 중심을 정의하고 싶습니다).

여기에 내가 원하는 것에 대한 설명이 있지만 개발자 중 한 명이 버그로 해석했으며 "쉽게 구현 [가능]"합니다.

답변

SeanCarter Nov 20 2020 at 20:14

의도 한대로 작동한다고 확신하지만 오류가 발견되면 수정 해주세요. ( 괴짜를 위해 괴짜들 과 함께 자갈 을 쌓았습니다 ) :


import sys

def distance(p1, p2): 
    return np.sum((p1 - p2)**2)


def find_remaining_centroid(data, known_centroids, k = 1): 
    ''' 
    initialized the centroids for K-means++ 
    inputs: 
        data - Numpy array containing the feature space
        known_centroid - Numpy array containing the location of one or multiple known centroids
        k - remaining centroids to be found
    '''
    n_points = data.shape[0]

    # Initialize centroids list
    if known_centroids.ndim > 1:
        centroids = [cent for cent in known_centroids]
    
    else:
        centroids = [np.array(known_centroids)]

    # Perform casting if necessary
    if isinstance(data, pd.DataFrame):
        data = np.array(data)
        
    # Add a randomly selected data point to the list  
    centroids.append(data[np.random.randint( 
            n_points), :])
    
    # Compute remaining k-1 centroids
    for c_id in range(k - 1):
        ## initialize a list to store distances of data 
        ## points from nearest centroid 
        dist = np.empty(n_points)

        for i in range(n_points):
            point = data[i, :] 
            d = sys.maxsize 

            ## compute distance of 'point' from each of the previously 
            ## selected centroid and store the minimum distance 
            for j in range(len(centroids)): 
                temp_dist = distance(point, centroids[j]) 
                d = min(d, temp_dist) 

            dist[i] = d

        ## select data point with maximum distance as our next centroid 
        next_centroid = data[np.argmax(dist), :] 
        centroids.append(next_centroid) 

        # Reinitialize distance array for next centroid
        dist = np.empty(n_points)
    

    
    return centroids[-k:]

사용법 :

# For finding a third centroid:
third_centroid = find_remaining_centroid(X_train, np.array([presence_seed, absence_seed]), k = 1)

# For finding the second centroid:
second_centroid = find_remaining_centroid(X_train, presence_seed, k = 1)

여기에서 Presence_seed 및 부재 _ 시드는 알려진 중심 위치입니다.