编程实现k均值算法,设置三组不同的k值、三组不同初始中心点,在西瓜数据集4.0上进行实验比较,并讨论什么样的初始中心有助于得到好结果。
下面所有图中的横坐标表示密度,纵坐标表示含糖率。
首先看看4.0数据集:
代码
#-*- coding:utf-8 -*-
"""
@Author: Victoria
@Date: 2017.10.24 12:00
"""
import random
import matplotlib.pyplot as plt
import xlrd
from copy import deepcopy
style = "*+o."
color = "kgybp"
class KMeans():
def __init__(self, k):
self.k = k
def train(self, X):
self.N = len(X)
self.d = len(X[0])
self.X = X
self.init()
self.init_centers = deepcopy(self.centers)
#self.centers = [[0.403, 0.237], [0.343, 0.099], [0.478, 0.437]]
#self.centers = [[0.403, 0.237], [0.343, 0.099], [0.532, 0.472]]
print self.centers
Js = []
iter = 0