K-means聚类算法有报错,大家来看看!

策略分享
标签: #<Tag:0x00007f73e54c36e0>

(candy) #1
克隆策略
In [31]:
#coding=utf-8
from numpy import *
import time  
import matplotlib.pyplot as plt  
In [86]:
startdate='2017-01-01'
enddate='2017-09-18'
instrument=D.instruments(startdate, enddate)
df=D.history_data(instrument,start_date=startdate,end_date=enddate,fields='close',period=None,groupped_by_instrument=False)
# dataMat=df['close'].values
df=df.pivot_table(index=['instrument'],columns=['date'])
dataMat=df.dropna(how='any')
In [85]:
# def loadDataSet(fileName):
#     dataMat = []
#     fr = open(fileName)
#     for line in fr.readlines():
#         curLine = line.strip().split('\t')
#         fltLine = map(float, curLine)
#         dataMat.append(fltLine)
#     return dataMat
    
#计算两个向量的距离,用的是欧几里得距离
def distEclud(vecA, vecB):
    return sqrt(sum(power(vecA - vecB, 2)))

#随机生成初始的质心(ng的课说的初始方式是随机选K个点)    
def randCent(dataSet, k):
    n = shape(dataSet)[1]
    centroids = mat(zeros((k,n)))
    for j in range(n):
        minJ = min(dataSet[:,j])
        rangeJ = float(max(array(dataSet)[:,j]) - minJ)
        centroids[:,j] = minJ + rangeJ * random.rand(k,1)
    return centroids
    
def kMeans(dataSet, k, distMeas=distEclud, createCent=randCent):
    m = shape(dataSet)[0]
    clusterAssment = mat(zeros((m,2)))#create mat to assign data points 
                                      #to a centroid, also holds SE of each point
    centroids = createCent(dataSet, k)
    clusterChanged = True
    while clusterChanged:
        clusterChanged = False
        for i in range(m):#for each data point assign it to the closest centroid
            minDist = inf
            minIndex = -1
            for j in range(k):
                distJI = distMeas(centroids[j,:],dataSet[i,:])
                if distJI < minDist:
                    minDist = distJI; minIndex = j
            if clusterAssment[i,0] != minIndex: 
                clusterChanged = True
            clusterAssment[i,:] = minIndex,minDist**2
#         print centroids
        for cent in range(k):#recalculate centroids
            ptsInClust = dataSet[nonzero(clusterAssment[:,0].A==cent)[0]]#get all the point in this cluster
            centroids[cent,:] = mean(ptsInClust, axis=0) #assign centroid to mean 
    return centroids, clusterAssment
    
def show(dataSet, k, centroids, clusterAssment):
    from matplotlib import pyplot as plt  
    numSamples, dim = dataSet.shape  
    mark = ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', '<r', 'pr']  
    for i in xrange(numSamples):  
        markIndex = int(clusterAssment[i, 0])  
        plt.plot(dataSet[i, 0], dataSet[i, 1], mark[markIndex])  
    mark = ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '<b', 'pb']  
    for i in range(k):  
        plt.plot(centroids[i, 0], centroids[i, 1], mark[i], markersize = 12)  
    plt.show()
      
# def main():
#     dataMat = mat(loadDataSet('testSet.txt'))
myCentroids, clustAssing= kMeans(dataMat,4,distMeas=distEclud, createCent=randCent)
# #     print myCentroids
# show(dataMat, 4, myCentroids, clustAssing)  
    
    
# if __name__ == '__main__':
#     main()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-85-7dc9cb5174a2> in <module>()
     62 # def main():
     63 #     dataMat = mat(loadDataSet('testSet.txt'))
---> 64 myCentroids, clustAssing= kMeans(dataMat,4,distMeas=distEclud, createCent=randCent)
     65 # #     print myCentroids
     66 # show(dataMat, 4, myCentroids, clustAssing)

<ipython-input-85-7dc9cb5174a2> in kMeans(dataSet, k, distMeas, createCent)
     28     clusterAssment = mat(zeros((m,2)))#create mat to assign data points
     29                                       #to a centroid, also holds SE of each point
---> 30     centroids = createCent(dataSet, k)
     31     clusterChanged = True
     32     while clusterChanged:

<ipython-input-85-7dc9cb5174a2> in randCent(dataSet, k)
     19     centroids = mat(zeros((k,n)))
     20     for j in range(n):
---> 21         minJ = min(dataSet[:,j])
     22         rangeJ = float(max(array(dataSet)[:,j]) - minJ)
     23         centroids[:,j] = minJ + rangeJ * random.rand(k,1)

TypeError: '(slice(None, None, None), Timestamp('1970-01-01 00:00:00'))' is an invalid key
In [ ]:
 
In [ ]: