解释代码def randCent(dataSet, k): m, n = dataSet.shape centroids = np.zeros((k, n)) for i in range(k): index = int(np.random.uniform(0, m)) # centroids[i, :] = dataSet[index, :] return centroids
时间: 2023-05-26 15:01:05 浏览: 139
这段代码定义了一个函数randCent,它有两个输入参数:dataSet和k。这个函数的作用是生成k个随机中心点,并将这些点存在centroids数组中。dataSet是一个矩阵,m是dataSet的行数,n是dataSet的列数。centroids数组是一个k行n列的全零矩阵,用来存储k个随机中心点。随机中心点是通过从0-m之间随机选择一个整数来确定dataSet中的某个点作为中心点的。该函数最后返回centroids数组。
相关问题
def findClosestCentroids(X, centroids): #定义函数findClosestCentroids """ Returns the closest centroids in idx for a dataset X where each row is a single example. """ K = centroids.shape[0] #获得数组centroids的行数并赋值给K idx = np.zeros((X.shape[0],1)) #定义idx为X.shape[0]行1列的零数组 temp = np.zeros((centroids.shape[0],1)) #定义temp为centroids.shape[0]行1列的数组 for i in range(X.shape[0]): #i遍历循环X.shape[0] for j in range(K): #j遍历循环K dist = X[i,:] - centroids[j,:] # length = np.sum(dist**2) temp[j] = length idx[i] = np.argmin(temp)+1 return idx 给这段代码注释
# 定义函数findClosestCentroids,它接受两个参数:数据集X和聚类中心centroids
# 函数的作用是为数据集中的每个样本找到距离它最近的聚类中心,并将其对应的聚类中心下标存储在idx中
# 获取聚类中心的数量K
K = centroids.shape[0]
# 初始化idx为X.shape[0]行1列的零数组
idx = np.zeros((X.shape[0],1))
# 初始化temp为centroids.shape[0]行1列的数组
temp = np.zeros((centroids.shape[0],1))
# 遍历数据集X中的每个样本
for i in range(X.shape[0]):
# 遍历每个聚类中心
for j in range(K):
# 计算当前样本到聚类中心的距离
dist = X[i,:] - centroids[j,:]
# 将距离的平方和存储在temp数组中
length = np.sum(dist**2)
temp[j] = length
# 找到距离当前样本最近的聚类中心下标,并将其加1存储在idx中
idx[i] = np.argmin(temp)+1
# 返回存储聚类中心下标的idx
return idx
代码改进:import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt from sklearn.datasets import make_blobs def distEclud(arrA,arrB): #欧氏距离 d = arrA - arrB dist = np.sum(np.power(d,2),axis=1) #差的平方的和 return dist def randCent(dataSet,k): #寻找质心 n = dataSet.shape[1] #列数 data_min = dataSet.min() data_max = dataSet.max() #生成k行n列处于data_min到data_max的质心 data_cent = np.random.uniform(data_min,data_max,(k,n)) return data_cent def kMeans(dataSet,k,distMeans = distEclud, createCent = randCent): x,y = make_blobs(centers=100)#生成k质心的数据 x = pd.DataFrame(x) m,n = dataSet.shape centroids = createCent(dataSet,k) #初始化质心,k即为初始化质心的总个数 clusterAssment = np.zeros((m,3)) #初始化容器 clusterAssment[:,0] = np.inf #第一列设置为无穷大 clusterAssment[:,1:3] = -1 #第二列放本次迭代点的簇编号,第三列存放上次迭代点的簇编号 result_set = pd.concat([pd.DataFrame(dataSet), pd.DataFrame(clusterAssment)],axis = 1,ignore_index = True) #将数据进行拼接,横向拼接,即将该容器放在数据集后面 clusterChanged = True while clusterChanged: clusterChanged = False for i in range(m): dist = distMeans(dataSet.iloc[i,:n].values,centroids) #计算点到质心的距离(即每个值到质心的差的平方和) result_set.iloc[i,n] = dist.min() #放入距离的最小值 result_set.iloc[i,n+1] = np.where(dist == dist.min())[0] #放入距离最小值的质心标号 clusterChanged = not (result_set.iloc[:,-1] == result_set.iloc[:,-2]).all() if clusterChanged: cent_df = result_set.groupby(n+1).mean() #按照当前迭代的数据集的分类,进行计算每一类中各个属性的平均值 centroids = cent_df.iloc[:,:n].values #当前质心 result_set.iloc[:,-1] = result_set.iloc[:,-2] #本次质心放到最后一列里 return centroids, result_set x = np.random.randint(0,100,size=100) y = np.random.randint(0,100,size=100) randintnum=pd.concat([pd.DataFrame(x), pd.DataFrame(y)],axis = 1,ignore_index = True) #randintnum_test, randintnum_test = kMeans(randintnum,3) #plt.scatter(randintnum_test.iloc[:,0],randintnum_test.iloc[:,1],c=randintnum_test.iloc[:,-1]) #result_test,cent_test = kMeans(data, 4) cent_test,result_test = kMeans(randintnum, 3) plt.scatter(result_test.iloc[:,0],result_test.iloc[:,1],c=result_test.iloc[:,-1]) plt.scatter(cent_test[:,0],cent_test[:,1],color = 'red',marker = 'x',s=100)
这段代码实现的是k-means聚类算法,但是有一些地方可以改进:
1. 函数kMeans中的createCent参数可以通过修改为直接传入质心的方式来更加灵活。
2. 函数kMeans中的distMeans参数可以修改为scipy库中的距离函数,如scipy.spatial.distance.cdist,来提高计算效率。
3. 函数kMeans中的clusterAssment可以使用pd.DataFrame来进行初始化,这样可以避免使用np.zeros和np.inf来进行初始化。
改进后的代码如下:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from scipy.spatial.distance import cdist
def randCent(dataSet, k):
"""
随机生成k个质心
"""
n = dataSet.shape[1] # 列数
data_min = dataSet.min()
data_max = dataSet.max()
# 生成k行n列处于data_min到data_max的质心
data_cent = np.random.uniform(data_min, data_max, (k, n))
return data_cent
def kMeans(dataSet, k, createCent=randCent, distMeans=cdist):
"""
k-means聚类算法
"""
centroids = createCent(dataSet, k) # 初始化质心,k即为初始化质心的总个数
result_set = pd.concat([pd.DataFrame(dataSet), pd.DataFrame()], axis=1, ignore_index=True)
# 将数据进行拼接,横向拼接,即将该容器放在数据集后面
clusterChanged = True
while clusterChanged:
clusterChanged = False
dist = distMeans(dataSet, centroids, metric='euclidean')
clusterAssment = np.argmin(dist, axis=1)
result_set.iloc[:, -1] = pd.Series(clusterAssment)
for i in range(k):
cent_df = result_set[result_set.iloc[:, -1] == i].mean() # 按照当前迭代的数据集的分类,进行计算每一类中各个属性的平均值
if not cent_df.empty:
centroids[i] = cent_df.iloc[:-1].values # 当前质心
clusterChanged = True
return centroids, result_set
x = np.random.randint(0, 100, size=100)
y = np.random.randint(0, 100, size=100)
randintnum = pd.concat([pd.DataFrame(x), pd.DataFrame(y)], axis=1, ignore_index=True)
cent_test, result_test = kMeans(randintnum, 3)
plt.scatter(result_test.iloc[:, 0], result_test.iloc[:, 1], c=result_test.iloc[:, -1])
plt.scatter(cent_test[:, 0], cent_test[:, 1], color='red', marker='x', s=100)
```
阅读全文