关于单个numpy数组中的多个numpy数组的维初始化的问题 [英] Questions regarding the dimension initialization of multiple numpy arrays within a single numpy array

查看:99
本文介绍了关于单个numpy数组中的多个numpy数组的维初始化的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我们有3个 Pauli矩阵,每个维度均为(2x2).如下图所示:

Given that we have 3 Pauli matrices, each with dimension (2x2). As shown below:

X = np.array([[0, 1], [1, 0]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]], dtype=complex)
Z = np.array([[1, 0], [0, -1]], dtype=complex)

现在,如果我将这些单独的(2x2)矩阵作为另一个(2x2)矩阵的条目.说:

Now if I put these each individual (2x2) matrices as entries to another (2x2) matrices. Say:

A = np.array([[X, 0], [0, Y]])
B = np.array([[X, X], [Y, Y]])

奇怪的是,A的暗淡为(2x2),这是我想要的,而B的暗淡为(2、2、2、2),无论如何,如下所示.

Weirdly, A has a dim of (2x2) - which is ideally what I want - and B has a dim of (2, 2, 2, 2)whatever this is, as show below

A = np.array([[X, 0], [0, Y]])

A.shape
Out[131]: (2, 2)

B = np.array([[X, X], [Y, Y]])

B.shape
Out[133]: (2, 2, 2, 2)

另一方面,假设C(1x3)矩阵,而D(1x2)矩阵,例如

On the other hand, say let C be a (1x3) matrix and D be a (1x2) matrix, e.g.

C = np.array([[X, Y, 0]])
D = np.array([[X, Y]])

再次,如果我们看一下初始化矩阵的维数

again if we look at the dimensions of the initialized matrices

C = np.array([[X, Y, 0]])

C.shape
Out[136]: (1, 3)

D = np.array([[X, Y]])

D.shape
Out[138]: (1, 2, 2, 2)

因此,似乎每当我在这样的数组中初始化数组时,如果存在混合数据类型作为条目(例如像AC中那样的矩阵和整数),它就会给我想要的合理形状,即维度(2,2),每个条目的隐藏"尺寸为(2x2).但是,一旦条目只是严格的矩阵(如BD中的矩阵),它就给了我不合理的维度,例如(2, 2, 2, 2).所以我的问题是:

So it seems that whenever I initialize arrays in an array like these, if there's mixed data type as entries i.e. matrices and integers like in AandC, it gives me the sensible shape that I want i.e. dimension(2,2), with "hidden" dimensions of (2x2) for each entries. But as soon as the entries are just strictly matrices like in BandD, it gives me insensible dimension such as (2, 2, 2, 2). So my question is:

如何以严格的(2, 2)矩阵作为条目初始化(n, n) numpy数组(矩阵),并且仍然保留其(n, n)维度,即不要给我一些奇怪的numpy维度(w, x, y, z)?/strong>

How do I initialize an (n, n) numpy array(matrix) with strictly (2, 2) matrices as entries, and still preserve its (n, n) dimensionality i.e. instead of giving me some weird numpy dimension (w, x, y, z)?

之所以想要这样做,是因为我正在量子力学中用算符进行运算,这些Pauli矩阵(例如XYZ)用作量子计算中的量子门.因此,如果我有一些状态rho,它也是一个(2x2)矩阵.让

The reason why I want this is because I'm doing computations with operators in quantum mechanics, with these Pauli matrices, such as the X, Y and Z, as quantum gates in quantum computation. So if I have some state rho which is also a (2x2) matrix. Let

rho = np.array([[1, 0],
                [0, 0]])

然后让RHO(2x2)对角矩阵,其条目是(2x2) rho矩阵.

And let RHO be the (2x2) diagonal matrix who's entries are the (2x2) rho matrices.

RHO = np.array([[rho, 0],
                [0, rho]])

我希望计算类似np.dot(D, RHO)的东西,这样它就可以给出

I wish to compute something like np.dot(D, RHO) such that it gives

np.array([np.dot(X, rho), 0],
         [0, np.dot(Y, rho)])

我已经在python上检查了两个(2x2)矩阵的点积与(2x2)矩阵作为条目,其条目乘法也都是点积.

And I've checked on python that the dot products of two (2x2) matrices with (2x2) matrices as entries, its entries multiplications will all be dot product too.

我上面提到的所有内容的动机是,我希望使用这些属性作为矢量化算法的手段.目前,我算法的一个非常粗糙的示例看起来像这样:

My motivation for all of the stuff I've talked about above is that I'm hoping to use these properties as means to vectorize my algorithm. Currently a very crude example of my algorithm looks something like this:

for i in (integer_1):
    for j in (integer_2):
        #do something that involves operations with sums of dot products of many matrices#

对其进行矢量化处理,使其有可能成为

and vectorize it so that it could potentially become

for i in (integer_1):
        #do something that involves operations with multiples of matrices with dot product of matrices as its entries#

哪个可能有效,否则可能无效!但是我很好奇我的这种方法是否会加快速度. 我希望我已经很好地解释了我的问题. 预先感谢.

Which might potentially work, or not! But I'm curious to see if this method of mine will produce a speed up. I hope I've explained my problems well. Thanks in advance.

编辑(1)

我已经添加了乳胶格式的数学,希望您能理解我在做什么.

def compute_channel_operation(rho, operators):
    """
    Given a quantum state's density function rho, the effect of the
    channel on this state is:
    rho -> sum_{i=1}^n E_i * rho * E_i^dagger
    Args:
        rho (2x2 matrix): Density function
        operators (list): List of operators(matrices)
    Returns:
        number: The result of applying the list of operators
    """
    operation = [E@rho@E.conj().T for i, E in enumerate(operators)]
    return np.sum(operation, axis=0)

因此,我希望张量方法的这种直接乘法可能不是使用循环,而是当我扩大仿真速度时,可以说必须执行一百万次 问题是K在这里应该是任何(1xn)维的列表,即[I]或[I,X]或[I,X,Y]或[I,X,Y,Z].我知道这里X = X ^ {\ dagger},Y和Z也一样,但是我会在仿真中遇到这种情况.

So then I was hoping that instead of using loops, this direct multiplication of tensor method might be quicker as I scale up my simulation, say having to do this 1 million times The thing is K here should be a list of any (1xn) dimensions i.e. [I] or [I, X] or [I, X, Y] or [I, X, Y, Z]. I understand that here X = X^{\dagger} and so will Y and Z, but I'll have situations in my simulation where that wont be the case.

我希望我现在已经清楚地解释了.

I hope I've now explained it clearly.

推荐答案

(2, 2, 2, 2)并不是奇怪的维度,它只是形状为2x2x2x2的4D张量

(2, 2, 2, 2) is not a weird dimension, it is just a 4D tensor of shape 2x2x2x2

之所以要为AB选择不同的形状,是因为您要使用标量0而不是2x2零矩阵来设置A.更改为

The reason why you are seing different shapes for A and B is because you are setting A with a scalar 0 instead of a 2x2 zero matrix. Change it to

A = np.array([[X, np.zeros((2, 2))], [np.zeros((2, 2)), Y]])
B = np.array([[X, X], [Y, Y]])

您将同时获得2x2x2x2张量.

And you will get 2x2x2x2 tensors for both.

或将其更改为

C = np.vstack([
    np.hstack([X, np.zeros((2, 2))]),
    np.hstack([np.zeros((2, 2)), Y])
])
D = np.vstack([
    np.hstack([X, X]),
    np.hstack([Y, Y])
])

您将获得4x4矩阵.

您还可以使用

E = A.transpose(0, 2, 1, 3).reshape(4, 4)
F = B.transpose(0, 2, 1, 3).reshape(4, 4)

np.allclose(C, E)  # True
np.allclose(D, F)  # True

然后返回

G = E.reshape(2, 2, 2, 2).transpose(0, 2, 1, 3)
H = F.reshape(2, 2, 2, 2).transpose(0, 2, 1, 3)

np.allclose(A, G)  # True
np.allclose(B, H)  # True

编辑:关于功能compute_channel_operation(),如果不执行列表理解但将操作矢量化并传递所有操作的3D张量,则可以大大提高其功能

Regarding your function compute_channel_operation(), you can speed it up considerably if you don't perform a list comprehension but vectorize the operation and pass in a 3D tensor with all your operations

rho = np.random.rand(2, 2)
operators = [np.random.rand(2, 2) for _ in range(1000)]
operators_tensor = np.asarray(operators)  # same as np.random.rand(1000, 2, 2)

def compute_channel_operation(rho, operators):
    operation = [E@rho@E.conj().T for i, E in enumerate(operators)]
    return np.sum(operation, axis=0)

def compute_channel_operation2(rho, operators):
    return np.sum(operators @ rho @ operators.transpose(0, 2, 1).conj(), axis=0)

A = compute_channel_operation(rho, operators)
B = compute_channel_operation(rho, operators_tensor)
C = compute_channel_operation2(rho, operators_tensor)

np.allclose(A, B) # True
np.allclose(A, C) # True

%timeit compute_channel_operation(rho, operators)
# 6.95 ms ± 103 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit compute_channel_operation(rho, operators_tensor)
# 7.53 ms ± 141 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit compute_channel_operation2(rho, operators_tensor)
# 416 µs ± 12 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

这篇关于关于单个numpy数组中的多个numpy数组的维初始化的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆