美文网首页
kMeans实现源码错误

kMeans实现源码错误

作者: 路人乙yh | 来源:发表于2018-11-02 23:16 被阅读13次

学习《机器学习实战》Ch10 kMeans聚类时,这本书附带的源码有不少错误或者需要修改的地方,此贴记录。

电脑:小米笔记本pro
python版本:5.5.1

错误

  1. 源码是基于python2的,所有的print ''text''都需要改为print('text').
  2. python2中的newlist = map(func, iterater)语法返回的是内存地址,在python3中需要改为newlist = list(map(func, iterater))
    这是我自己改的代码,返回值与书本的代码不同
def loadDataSet(fileName):
  dataMat = []
  fr = open(fileName)
  for line in fr.readlines():
      curLine = line.strip().split('\t')
      fltLine = list(map(float, curLine))
      dataMat.append(fltLine)
      data = np.array(dataMat).reshape(-1, 2)
  return data
  1. 我发现《机器学习实战》这本书的源码使用的几乎都是np.mat()而不是np.array(),在这下面段代码第三行中我尝试使用array,
def randCent(dataSet, k):
    n = dataSet.shape[1]
    centroids = np.array(np.zeros((k, n)))
    #随机构建簇质心
    for j in range(n):
        minJ = np.min(dataSet[:,j])
        rangeJ = float(np.max(dataSet[:,j]) - minJ)
        centroids[:,j] = minJ + rangeJ * np.random.rand(k, 1)#得到(k,1)个从0到1之间的小数
    return centroids

结果运行出错
could not broadcast input array from shape (2,1) into shape (2)
改为mat就没有问题,经过查阅资料发现了原因:
centroids是一个(k,n)的数组array,centroids[:,j]返回的是一个一维的数组(比如array([1.0, 2.0, 3.0]),而np.random.rand(k, 1)是一个(n,1)的数组(比如array([[1.0],[2.0],[3.0]]),这就是刚才报出的错误形状不一样不能进行操作。

关于array和matrix的更多讨论
如果上面的centroids = np.mat(np.zeros((k, n)))注意换成了mat,此时centroids[:,j]是一个(k,1)的矩阵。
在jupyter notebook中再举几个例子加深理解:
下图红线块中x是一个数组,引用x[:,0]得到的是个一维的数组;
蓝线块中的x_mat是个矩阵,引用x_mat[:,0]得到的是个(3,1)的矩阵。

temp2.PNG

相关文章

网友评论

      本文标题:kMeans实现源码错误

      本文链接:https://www.haomeiwen.com/subject/cushxqtx.html