我有两个形状为(130,64,2048)的列表,将其称为(s,f,b),一个长度为64的向量,称为v。我需要将这两个列表附加在一起以构成一个列表(130、2、64、2048)的形状,然后将f [i]中的所有2048个值乘以v的第i个值。
输出数组还需要具有形状(130、2、64、2048)
显然,这两个步骤可以互换进行。我想知道做这种事情的最Python方式。
我的主要问题是我的代码花了很多时间将列表变成一个numpy数组,这对于我的某些计算是必需的。我有:
new_prof = np.asarray( new_prof )
但是,对于我的列表的大小和形状,这似乎要花费两个时间。关于如何更好地进行初始化的任何想法?
我的尝试表明了上述问题:
# Converted data should have shape (130, 2, 64, 2048)
converted_data = IQUV_to_AABB( data, basis = "cartesian" )
new_converted = np.array((130, 2, 64, 2048))
# I think s.shape is (2, 64, 2048) and cal_fa has length 64
for i, s in enumerate( converted_data ):
aa = np.dot( s[0], cal_fa )
bb = np.dot( s[1], cal_fb )
new_converted[i].append( (aa, bb) )
但是,此代码不起作用,我认为它与点积有关。也许吗?
我还想知道为什么将列表更改为numpy数组需要这么长时间。
答案 0 :(得分:1)
尝试从小处着手,并在控制台中查看结果:
import numpy as np
x = np.arange(36)
print(x)
y = np.reshape(x, (3, 4, 3))
print(y)
# this is a vector of the same size as dimension 1
a = np.arange(4)
print(a)
# expand and let numpy's broadcasting do the rest
# https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
# https://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc
b = a[np.newaxis, :, np.newaxis]
print(b)
c = y * b
print(c)
您可以阅读有关np.newaxis
here,here和here的信息。
使用numpy.append
的速度相当慢,因为它必须预先分配内存并每次复制整个数组。 numpy数组是连续的内存块。
如果计算机内存不足,则可能必须使用它。但是在这种情况下,请尝试遍历适当的块,直到您的计算机仍能处理它们。有时,重新设置尺寸是一种加快计算速度的方法。