假设
1。我定义了一个返回距离值的函数foo
2。我有一个组列表(在我的例子中也是列表),每个组都包含一些变量。
3. 不同组中的变量是不同的,也就是说没有重复
4. 这些群组的长度> = 1,(非空),< =变量总数,因为没有重复
任务:我应该浏览整个变量列表,使用预定义函数foo
检查它是否与当前组“最接近”。如果是,它仍然在组中,如果它更接近另一组,我将其重新分配给更近的组。如果发生重新分配,我会重复所有先前变量的过程,以查看新组是否影响其分配。我继续迭代以前的变量,直到它们根据foo“放置好”。然后我转到下一个变量(如果上一次迭代改变了分组,那么这个迭代会检查当前变量和新组之间的距离)。
要点是:重新分配到群组是基于foo返回的距离,每次重新分配都会触发前一个变量的循环。 (以前这里应该是关于原始组的初始排序。)
请考虑以下示例:
简要示例
# In my example, my variables
[[1, 2], [5, 8], [3, 4], [7, 9]]
# Suppose that here we define distance between an element and a list
# by the difference between the element and the list's average
# Suppose we do not reassign if a number is equally as close to it's current
# group and another group
# and assume an empty set is the same as a set that only contains 0
# the first group does not experience change as its elements are closest to itself
[[1, 2], [8], [3, 4, 5], [7, 9]]
# 5 is moved to the third group since it's closer to 3.5 than it is to 1.5, 8 and 8
# We then consider the first group again to see if they require reassignment
# after the group changes. Luckily we do not.
# this is an important step as 1 is now equally close to [2] and [0].
[[1, 2], [], [3, 4, 5], [7, 9, 8]]
# 8 is moved to last group since 8 is closest to 8
# we would now check to see if the reassignment of 8
# would cause 1, 2, or 5 to be reassigned, the answer is no here.
[[1, 2], [], [3, 4, 5], [7, 9, 8]]
# We will let 3 remain since it is equally as close to (1+2)/2 and (4+5)/2
# 4 and 5 remain in their current group, and then 7,9,8 remain as well.
# The preferred final result would then look something like:
[[1, 2], [3, 4, 5], [7, 9, 8]]
# Since we require all groups be non-empty, we removed the empty list.
对于每个变量,我必须“循环”通过所有组,并且对于每次重新分配,我可能必须循环遍历所有先前的变量。
如何最有效地完成这项工作?
目前我有两种方法,
1. 循环遍历所有变量而不检查先前的赋值,然后使用第一个循环的结果循环遍历所有变量,并继续循环以前的结果,直到不能对任何变量进行更改。 (有点像牛顿方法用于寻找根的方式)
在一些变量不断前后移动,可能需要很长的运行时间的情况下,关注的可能是无限循环。
2. 每次重新分配时都要检查以前的变量。 也存在无限循环的可能性。另外,如果第一个变量被重新分配,我们可以继续到第二个,但是如果最后一个变量被重新分配,我们可能需要多次检查所有变量。这可能非常昂贵。
其他评论:我尝试使用python(2.7)'集群'变量,其方式与SAS默认maxeigen=1
varclus 的方式类似使用hierarchy
选项的过程。我尝试了包 sklearn 和 scipy 提供的各种方法,但生成的集群与sas过程输出的集群不同。对此提出的任何建议都会有所帮助,否则这只是与元素重新分配问题无关的其他信息。
答案 0 :(得分:0)
我在R中实现了相同的功能,并根据SAS文档使用了以下内容“变量到集群的迭代重新分配分两个阶段进行。第一个是最近的组件排序(NCS)阶段,原则上类似于最近的质心排序Anderberg(1973)描述的算法。在每次迭代中,计算集群组件,并将每个变量分配给与其具有最高平方相关性的组件。第二阶段涉及搜索算法,其中每个变量都经过测试以查看如果将其分配给不同的集群,则增加了解释的方差量。如果在搜索阶段重新分配变量,则在测试下一个变量之前重新计算所涉及的两个集群的组件.NCS阶段比搜索阶段快得多但更有可能被局部最优困住。“ https://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_varclus_sect001.htm varclus中的变量重新分配分两步进行
变量(i)与群集(j)的平方相关可以定义为: (变量(i)与集群中变量的相关性的向量(j)%*%集群的第一主成分(j)/ sqrt(集群的第一特征值(j))^ 2
此处:%*%矩阵乘法