Pandas 种子和num_运行在KMeans集群中的重要性
对于ML来说是新的,所以尝试理解下面的代码。具体地Pandas 种子和num_运行在KMeans集群中的重要性,pandas,machine-learning,pyspark,cluster-analysis,hierarchical-clustering,Pandas,Machine Learning,Pyspark,Cluster Analysis,Hierarchical Clustering,对于ML来说是新的,所以尝试理解下面的代码。具体地 在np.arange(1,num_runs+1)中运行的,,这个循环需要什么?为什么作者没有使用KMeans的setMaxIter方法 在集群中播种的重要性是什么 为什么作者选择显式设置种子而不是使用默认种子 根据我对材料的阅读,我会尽力回答你的问题 这个循环的原因是作者使用int(np.random.randint(100,size=1))为每个循环设置了一个新的seed。如果特征变量显示的模式自动将它们分组到可见簇中,则起始种子不应影响最终
,
,这个循环需要什么?为什么作者没有使用KMeans
的setMaxIter
方法根据我对材料的阅读,我会尽力回答你的问题
int(np.random.randint(100,size=1))
为每个循环设置了一个新的seed
。如果特征变量显示的模式自动将它们分组到可见簇中,则起始种子不应影响最终簇成员资格。但是,如果数据是均匀分布的,那么我们可能会根据初始随机变量得到不同的集群成员。我相信作者正在为每次运行更改这些种子,以测试不同的初始分布。使用setMaxIter
将为相同的seed
(初始分发)设置最大迭代次数k
点的初始分布。根据您的基础数据分布,集群可以在不同的最终分布中聚合from pyspark.ml.clustering import KMeans
from pyspark.ml.evaluation import ClusteringEvaluator
def optimal_k(df_in,index_col,k_min, k_max,num_runs):
'''
Determine optimal number of clusters by using Silhoutte Score Analysis.
:param df_in: the input dataframe
:param index_col: the name of the index column
:param k_min: the train dataset
:param k_min: the minmum number of the clusters
:param k_max: the maxmum number of the clusters
:param num_runs: the number of runs for each fixed clusters
:return k: optimal number of the clusters
:return silh_lst: Silhouette score
:return r_table: the running results table
:author: Wenqiang Feng
:email: von198@gmail.com.com
'''
start = time.time()
silh_lst = []
k_lst = np.arange(k_min, k_max+1)
r_table = df_in.select(index_col).toPandas()
r_table = r_table.set_index(index_col)
centers = pd.DataFrame()
for k in k_lst:
silh_val = []
for run in np.arange(1, num_runs+1):
# Trains a k-means model.
kmeans = KMeans()\
.setK(k)\
.setSeed(int(np.random.randint(100, size=1)))
model = kmeans.fit(df_in)
# Make predictions
predictions = model.transform(df_in)
r_table['cluster_{k}_{run}'.format(k=k, run=run)]= predictions.select('prediction').toPandas()
# Evaluate clustering by computing Silhouette score
evaluator = ClusteringEvaluator()
silhouette = evaluator.evaluate(predictions)
silh_val.append(silhouette)
silh_array=np.asanyarray(silh_val)
silh_lst.append(silh_array.mean())
elapsed = time.time() - start
silhouette = pd.DataFrame(list(zip(k_lst,silh_lst)),columns = ['k', 'silhouette'])
print('+------------------------------------------------------------+')
print("| The finding optimal k phase took %8.0f s. |" %(elapsed))
print('+------------------------------------------------------------+')
return k_lst[np.argmax(silh_lst, axis=0)], silhouette , r_table