2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
如果您想獲得真正的矢量化處理,則需要使用諸如 numpy 之類的庫(kù)。但是這些可能會(huì)限制您可以支持的數(shù)據(jù)類型,以便允許 GPU 進(jìn)行處理。
在任何一種情況下,您都可以使用字典來(lái)展平結(jié)構(gòu)并促進(jìn)結(jié)構(gòu)元素的批處理。這將是一個(gè)以元組作為鍵的字典,其中元組中的每個(gè)條目表示該級(jí)別的值索引:
例如:
[
[ [1,2] , [3,4,5] ],
[ [6,7,8] , [9] , [10] , [11,12] ],
[ [13] , [14,15] , [16,17,18] ]
]
可以在這樣的字典中表示為:
{
(0,0,0) : 1,
(0,0,1) : 2,
(0,1,0) : 3,
(0,1,1) : 4,
(0,1,2) : 5,
(1,0,0) : 6,
(1,0,1) : 7,
(1,0,2) : 8,
(1,1,0) : 9,
(1,2,0) : 10,
(1,3,0) : 11,
(1,3,1) : 12,
(2,0,0) : 13,
(2,1,0) : 14,
(2,1,1) : 15,
(2,1,0) : 16,
(2,1,1) : 17,
(2,1,2) : 18
}
這也可以使用兩個(gè)數(shù)組(一個(gè)用于級(jí)別索引,一個(gè)用于數(shù)據(jù))在 numpy 中表示
這種類型的結(jié)構(gòu)之間的處理將提供樹(shù)結(jié)構(gòu)中葉值的快速遍歷,同時(shí)保持分支之間的關(guān)系。
例如:
# sum of values under second branch:
result = sum( value for level,value in data.items() if level[0] == 1 )
# or using numpy:
result = np.sum(data[levels[:,0]==1])
# adding two structures:
result = { k:data1.get(k,0)+data2.get(k,0) for k in set((*data1,*data2)) }
# or using numpy (assuming same levels in both structures)
resultLevels, resultData = levels1,data1+data2
# numpy adding structures with different levels is a bit more involved
# but still feasible.

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
謝阿蘭 T。
我已經(jīng)使用了你的想法并編寫(xiě)了這個(gè)類來(lái)處理我的數(shù)據(jù)。這樣,我可以像使用 numpy 數(shù)組一樣使用 slice 訪問(wèn)我的元素,并且可以將 data 參數(shù)(扁平數(shù)據(jù))與 numpy 矢量化函數(shù)一起使用:
class DataStructure():
__slots__ = ["data", "positions"]
def __init__(self, data, place):
self.data = np.array(data)
self.positions = np.array(place)
def __getitem__(self, item):
item = (item,) if not isinstance(item, tuple) else item
mask = np.full((len(self.positions),), True)
for i, selection in enumerate(item):
if not isinstance(selection, slice):
mask &= self.positions[:, i] == selection
else:
start, stop, step = selection.indices(len(self.positions))
mask &= np.isin(self.positions[:,i], range(start,stop,step))
return self.data[mask]
PS:不要猶豫告訴我它是否可以優(yōu)化,特別是我使用切片。
添加回答
舉報(bào)