EEG上k-means的一次实验
我们尝试在EEG上进行最简单的k_means聚类并分析乐聚类结果和如若要进行下一步的研究所需要的特征提取。使用的是DEAP数据库
数据读取
data=np.loadtxt("/Users/rain/Downloads/EEG/DEAP/EEG_feature.txt")
#我们读入所有的可能的
label1=np.loadtxt("/Users/rain/Downloads/EEG/DEAP/valence_arousal_label.txt")
label2=np.loadtxt("/Users/rain/Downloads/EEG/DEAP/subject_video.txt")
计算欧式距离
def distEclud(x,y):
return np.sqrt(np.sum((x-y)**2))
产生随机的聚类中心
def randCent(dataSet,k):
m,n = dataSet.shape
#先将中心全置为0
centroids = np.zeros((k,n))
for i in range(k):
index = int(np.random.uniform(0,m)) #随机生成中心
centroids[i,:] = dataSet[index,:]
return centroids
进行聚类
def KMeans(dataSet,k):
m = np.shape(dataSet)[0] #行的数目
# 第一列存样本属于哪一簇
# 第二列存样本的到簇的中心点的误差
clusterAssment = np.mat(np.zeros((m,2)))
clusterChange = True
# 第1步 初始化centroids
centroids = randCent(dataSet,k)
while clusterChange:
clusterChange = False
# 遍历所有的样本(行数)
for i in range(m):
minDist = 100000.0
minIndex = -1
# 遍历所有的聚类中心
#第2步 找出最近的聚类中心
for j in range(k):
# 计算该样本到质心的欧式距离
distance = distEclud(centroids[j,:],dataSet[i,:])
if distance < minDist:
minDist = distance
minIndex = j
# 第 3 步:更新每一行样本所属的类
if clusterAssment[i,0] != minIndex:
clusterChange = True
clusterAssment[i,:] = minIndex,minDist**2
#第 4 步:更新聚类中心
for j in range(k):
pointsInCluster = dataSet[np.nonzero(clusterAssment[:,0].A == j)[0]] # 获取类所有的点
centroids[j,:] = np.mean(pointsInCluster,axis=0)
# 对矩阵的行求均值
print("Cluster complete!")
#返回聚类中心和聚类结果(包括分类和最小距离)
return centroids,clusterAssment
进行k-means分类
对k=2进行聚类
k=2
centroids,clusterAssment = KMeans(data,k)
kind=clusterAssment[:,0:1]
kind=np.reshape(kind,-1)
kind
kind[0,0:100]
matrix([[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,
0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,
0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,
0.,0.,0