defloadDataSet(fileName):#general function to parse tab -delimited floats
dataMat =[]#assume last column is target value
fr =open(fileName)for line in fr.readlines():
curLine = line.strip().split('\t')
fltLine =map(float,curLine)#map all elements to float()
dataMat.append(fltLine)return dataMat
defdistEclud(vecA, vecB):return sqrt(sum(power(vecA - vecB,2)))#la.norm(vecA-vecB)defrandCent(dataSet, k):
n = shape(dataSet)[1]
centroids = mat(zeros((k,n)))#create centroid matfor j inrange(n):#create random cluster centers, within bounds of each dimension
minJ =min(dataSet[:,j])
rangeJ =float(max(dataSet[:,j])- minJ)
centroids[:,j]= mat(minJ + rangeJ * random.rand(k,1))return centroids
K-均值聚类算法
defkMeans(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 =Truewhile clusterChanged:
clusterChanged =Falsefor i inrange(m):#for each data point assign it to the closest centroid
minDist = inf; minIndex =-1for j inrange(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**2print(centroids)for cent inrange(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
使用后处理来提高聚类性能
二分K-均值聚类算法
defbiKmeans(dataSet, k, distMeas=distEclud):
m = shape(dataSet)[0]
clusterAssment = mat(zeros((m,2)))
centroid0 = mean(dataSet, axis=0).tolist()[0]
centList =[centroid0]#create a list with one centroidfor j inrange(m):#calc initial Error
clusterAssment[j,1]= distMeas(mat(centroid0), dataSet[j,:])**2while(len(centList)< k):
lowestSSE = inf
for i inrange(len(centList)):
ptsInCurrCluster = dataSet[nonzero(clusterAssment[:,0].A==i)[0],:]#get the data points currently in cluster i
centroidMat, splitClustAss = kMeans(ptsInCurrCluster,2, distMeas)
sseSplit =sum(splitClustAss[:,1])#compare the SSE to the currrent minimum
sseNotSplit =sum(clusterAssment[nonzero(clusterAssment[:,0].A!=i)[0],1])print"sseSplit, and notSplit: ",sseSplit,sseNotSplit
if(sseSplit + sseNotSplit)< lowestSSE:
bestCentToSplit = i
bestNewCents = centroidMat
bestClustAss = splitClustAss.copy()
lowestSSE = sseSplit + sseNotSplit
bestClustAss[nonzero(bestClustAss[:,0].A ==1)[0],0]=len(centList)#change 1 to 3,4, or whatever
bestClustAss[nonzero(bestClustAss[:,0].A ==0)[0],0]= bestCentToSplit
print'the bestCentToSplit is: ',bestCentToSplit
print'the len of bestClustAss is: ',len(bestClustAss)
centList[bestCentToSplit]= bestNewCents[0,:].tolist()[0]#replace a centroid with two best centroids
centList.append(bestNewCents[1,:].tolist()[0])
clusterAssment[nonzero(clusterAssment[:,0].A == bestCentToSplit)[0],:]= bestClustAss#reassign new clusters, and SSEreturn mat(centList), clusterAssment
使用Apriori算法进行关联分析
Apriori算法
优点:易编码实现
缺点:在大数据集上可能较慢
适用数据类型:数值型或者标称型数据
Apriori算法的一般过程
①收集数据:使用任意方法
②准备数据:任何数据类型都可以,因为我们只保存集合
③分析数据:使用任意方法
④训练算法:使用Apriori算法来找到频繁项集
⑤测试算法:不需要测试过程
⑥使用算法:用于发现频繁项集以及物品之间的关联规则
Apriori算法中的辅助函数
defloadDataSet():return[[1,3,4],[2,3,5],[1,2,3,5],[2,5]]defcreateC1(dataSet):
C1 =[]for transaction in dataSet:for item in transaction:ifnot[item]in C1:
C1.append([item])
C1.sort()returnmap(frozenset, C1)#use frozen set so we#can use it as a key in a dict defscanD(D, Ck, minSupport):
ssCnt ={}for tid in D:for can in Ck:if can.issubset(tid):ifnot ssCnt.has_key(can): ssCnt[can]=1else: ssCnt[can]+=1
numItems =float(len(D))
retList =[]
supportData ={}for key in ssCnt:
support = ssCnt[key]/numItems
if support >= minSupport:
retList.insert(0,key)
supportData[key]= support
return retList, supportData
Apriori算法
defaprioriGen(Lk, k):#creates Ck
retList =[]
lenLk =len(Lk)for i inrange(lenLk):for j inrange(i+1, lenLk):
L1 =list(Lk[i])[:k-2]; L2 =list(Lk[j])[:k-2]
L1.sort(); L2.sort()if L1==L2:#if first k-2 elements are equal
retList.append(Lk[i]| Lk[j])#set unionreturn retList
defapriori(dataSet, minSupport =0.5):
C1 = createC1(dataSet)
D =map(set, dataSet)
L1, supportData = scanD(D, C1, minSupport)
L =[L1]
k =2whilelen(L[k -2])>0:
Ck = aprioriGen(L[k-2], k)
Lk, supK = scanD(D, Ck, minSupport)#scan DB to get Lk
supportData.update(supK)
L.append(Lk)
k +=1return L, supportData
关联规则生成函数
defgenerateRules(L, supportData, minConf=0.7):#supportData is a dict coming from scanD
bigRuleList =[]for i inrange(1,len(L)):#only get the sets with two or more itemsfor freqSet in L[i]:
H1 =[frozenset([item])for item in freqSet]if i >1:
rulesFromConseq(freqSet, H1, supportData, bigRuleList, minConf)else:
calcConf(freqSet, H1, supportData, bigRuleList, minConf)return bigRuleList
defcalcConf(freqSet, H, supportData, brl, minConf=0.7):
prunedH =[]#create new list to returnfor conseq in H:
conf = supportData[freqSet]/supportData[freqSet-conseq]#calc confidenceif conf >= minConf:print(freqSet-conseq,'-->',conseq,'conf:',conf)
brl.append((freqSet-conseq, conseq, conf))
prunedH.append(conseq)return prunedH
defrulesFromConseq(freqSet, H, supportData, brl, minConf=0.7):
m =len(H[0])iflen(freqSet)>(m +1):#try further merging
Hmp1 = aprioriGen(H, m+1)#create Hm+1 new candidates
Hmp1 = calcConf(freqSet, Hmp1, supportData, brl, minConf)iflen(Hmp1)>1:#need at least two sets to merge
rulesFromConseq(freqSet, Hmp1, supportData, brl, minConf)