【发布时间】:2015-06-14 15:10:47
【问题描述】:
我有一个 3D numpy 数组 arr,形状为 m*n*k。
对于沿m 轴的每组值(例如arr[:, 0, 0]),我想生成一个值来表示该组,以便最终得到一个二维矩阵n*k。
如果沿m 轴重复一组值,那么我们应该每次生成相同的值。
即这是一个哈希问题。
我使用字典创建了该问题的解决方案,但它大大降低了性能。对于每组值,我调用这个函数:
def getCellId(self, valueSet):
# Turn the set of values (a numpy vector) to a tuple so it can be hashed
key = tuple(valueSet)
# Try and simply return an existing ID for this key
try:
return self.attributeDict[key]
except KeyError:
# If the key was new (and didnt exist), try and generate a new Id by adding one to the max of all current Id's. This will fail the very first time we do this (as there will be no Id's yet), so in that case, just assign the value '1' to the newId
try:
newId = max(self.attributeDict.values()) +1
except ValueError:
newId = 1
self.attributeDict[key] = newId
return newId
数组本身的大小通常为 30*256*256,因此一组值将有 30 个值。 我随时都有数百个这样的数组要处理。 目前,完成所有需要完成的处理以计算哈希 100 个数组的块需要 1.3 秒。 包括高达 75 秒的散列颠簸。
有没有更快的方法来生成单个代表值?
【问题讨论】:
-
代表值一定要好看吗? ...或者它可以是“任何东西”?
-
@plonser:任何整数
-
所有这些数组的形状都相同吗
30 x 256 x 256? -
@divakar,是的,总是
-
我想知道是否会有基于 numpy.cross 的解决方案?这可能会带来非常好的性能。
标签: python arrays numpy dictionary hash