假设我想要一个大小为 (n,m)
的numpy数组,其中 n
非常大,但是有很多重复,即 . 0:n1
是相同的, n1:n2
是相同的等等( n2%n1!=0
,即不是规则的间隔) . 有没有办法只为每个重复项存储一组值,同时拥有整个数组的视图?
例:
unique_values = np.array([[1,1,1], [2,2,2] ,[3,3,3]]) #these are the values i want to store in memory
index_mapping = np.array([0,0,1,1,1,2,2]) # a mapping between index of array above, with array below
unique_values_view = np.array([[1,1,1],[1,1,1],[2,2,2],[2,2,2],[2,2,2], [3,3,3],[3,3,3]]) #this is how I want the view to look like for broadcasting reasons
我计划将数组(视图)乘以一些大小为 (1,m)
的其他数组,并取这个产品的点积:
other_array1 = np.arange(unique_values.shape[1]).reshape(1,-1) # (1,m)
other_array2 = 2*np.ones((unique_values.shape[1],1)) # (m,1)
output = np.dot(unique_values_view * other_array1, other_array2).squeeze()
输出是长度为 n
的1D数组 .
2 回答
您的表达式允许两个重要的优化:
做最后的索引
首先将
other_array1
与other_array2
相乘,然后使用unique_values
让我们应用这些优化:
如果我们观察到两件事情,很容易发现这些优化:
(1)如果
A
是mxn
-matrix而b
是n
-vector那么(2)如果
A
是一个mxn
-matrix而且I
是k
的k
整数,则range(m)
然后onehot
可以定义为使用这些事实并缩写
uv
,im
,oa1
和oa2
我们可以写现在,上述优化只是选择这些矩阵乘法的最佳阶数
使用(1)和(2)向后,我们从这篇文章的开头获得优化的表达式 .
根据您的示例,您可以简单地将通过计算的索引映射计算到最后: