ワインデータクラスタリング

14288 ワード

ワインデータクラスタリング
Wineデータセットは3種類の異なる起源からのワインの計178本の記録(計178種類のワイン)を含み、13の属性はワインの13種類の化学成分であり、化学分析によってワインの起源を推定することができる.178個の記録されたクラスタリングを完了し、データセット全体のデータを3つのクラスタリング(3つの異なる起源に対応するワイン)に分類するクラスタリング方法を実現することが要求される.
プログラムコード
'''
-*- coding:utf-8 -*-
  :2019-6-6    
  :zzx
  :       
'''
import random
import numpy as np
from sklearn import preprocessing
def selectInitMeanVec(Data,k):#        
    indexInitMeanVec = random.sample(range(m), k)
    initMeanVec = Data[indexInitMeanVec, :]
    return initMeanVec

def calcDistance(Data, k, MeanVec):#         
    Dist = np.zeros((k, 1))
    Label = np.zeros((m, 1))
    for i in range(m):
        for j in range(k):
            a = Data[i, :]-MeanVec[j, :]
            Dist[j] = np.sqrt(sum(a**2))
        Label[i] = np.argmin(Dist)
    return Label

def updateMeanVec(Data, Label, k, oldMeanVec):#      
    newMeanVec = np.zeros((k, n))
    numSamples = np.zeros((k, 1), dtype=int)
    for i in range(k):
        num = 0
        D = np.zeros((k, 0))
        for j in range(m):
            if Label[j] == i:
                D = np.append(D, Data[j, :])
                num += 1
                numSamples[i] = num
                D = np.reshape(D, (-1, n))
                newMeanVec[i, :] = np.mean(D, axis=0)
                #              ,               
                if num == 0:
                    newMeanVec[i, :] = oldMeanVec[i, :]
    return newMeanVec, numSamples

if __name__ == '__main__':
    data = np.loadtxt("wine.csv", delimiter=',')[:, 0:14]
    Data = preprocessing.scale(data)
    k = 3
    global m, n
    m, n = Data.shape
    initMeanVec = selectInitMeanVec(Data, k)
    oldMeanVec = initMeanVec.copy()
    Label = calcDistance(Data, k, initMeanVec)
    for i in range(200):
        newMeanVec, numSamples = updateMeanVec(Data, Label, k, oldMeanVec)
        oldMeanVec = newMeanVec.copy()
        Label = calcDistance(Data, k, newMeanVec)
        # print(Label, Data)
        print('--- %d     '%(i+1))
    print(numSamples)

    l = 1
    for L in Label:
        if 0 in Label[l]:
            print("    :%d" %l)
        elif 1 in Label[l]:
            print("    :%d" %l)
        elif 2 in Label[l]:
            print("    :%d" %l)
        else:
            pass
    l += 1