【问题标题】:How do I get faster redundancy reduction without nested for loop如何在没有嵌套 for 循环的情况下更快地减少冗余
【发布时间】:2017-07-13 14:25:14
【问题描述】:

我有一大段代码想尝试加快速度。如果那是解决这个问题的好方法,我一直在使用 tensorflow。这是我正在处理的大型模拟的一部分的代码。但是,此代码运行时间太长。我有一种方法可以改变它们在表面上划分的频率,截至目前,分辨率降低了 10 倍,这个循环运行了一个多小时。有没有人有任何加快速度的提示?

Points = PlanesList[0:3,0:3]
Indices = np.array([[0],[1],[2]])
print(np.prod(PlanesList[0,:].shape))
for k in range(1,int(np.prod(PlanesList[0,:].shape)/3)+1):
    for ind in range(1,int(np.prod(Points.shape)/3)+1):
        truths = np.array([False,False,False])
        if np.all(PlanesList[0:3,(3*k-3)] == Points[0:3,ind-1]):
            index1=ind-1
            truths[0] = True
        if np.all(PlanesList[0:3,(3*k-2)] == Points[0:3,ind-1]):
            index2=ind-1
            truths[1] = True
        if np.all(PlanesList[0:3,(3*k-1)] == Points[0:3,ind-1]):
            index3=ind-1
            truths[2] = True
    if truths[0] == False:
        Points = np.column_stack([Points,PlanesList[0:3,(3*k-3)]])
        index1 = np.prod(Points[0,:].shape)-1
    if truths[1] == False:
        Points = np.column_stack([Points,PlanesList[0:3,(3*k-2)]])
        index2 = np.prod(Points[0,:].shape)-1
    if truths[2] == False:
        Points = np.column_stack([Points,PlanesList[0:3,(3*k-1)]])
        index3 = np.prod(Points[0,:].shape)-1
    Tempind = np.array([[int(index1)],[int(index2)],[int(index3)]])
    Indices = np.column_stack([Indices,Tempind])

此代码的目的是从数组 PlanesList 中删除冗余。由于我创建数组的方式,我还没有想出一种方法来形成它而没有冗余。 PlanesList 是一个包含多组 3D 三角形的数组,为了稍后在模拟中,我需要能够定位这些三角形。第 0 行是 X 坐标,第 1 行是 Y,第 2 行是 Z。PlanesList 是一个二维数组,有超过 60,000 列(20,000 个三角形)和正好 3 行。

【问题讨论】:

  • 当您说删除冗余时,您的意思是 1,2,3 是否是删除所有其他 1,2,3 实例(3,2,1 或 213 或 231)的一个点?跨度>
  • 如果点是 (1,2,3),我想删除 (1,2,3) 的所有其他实例,因为我认为它肯定会发生 8 次。无论哪种方式,PlanesList 中的任何点都保证有另一个相同点的实例

标签: python arrays numpy tensorflow


【解决方案1】:

要将 numpy 数组中的相同列减少到一次,您可以使用 np.uniqueaxis 参数。

示例数据:

a = np.random.randint(0, 10, (3,10)) 
a[:,3] = a[:,0]  # Duplicate one column

减少:

a_reduced = np.unique(a, axis=1)

请注意,这将对您的数组进行排序。

另外,请注意 axis 参数是在 numpy 版本 1.13.0 中添加的。我假设底层实现很快,尽管可能存在专门针对您的问题量身定制的更快的解决方案。


编辑:如果您想知道减少点在整个数组中的索引,请使用return_index 参数:

a_reduced, a_indices = np.unique(a, axis=1, return_index=True)

【讨论】:

    猜你喜欢
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多