简体   繁体   English

Numpy - 如何使用此算法从 2d 中的 3d 矩阵传递

[英]Numpy - How pass from 3d matrix in 2d with this algorithm

I need to have a more efficient code, that the one implemented by me below.我需要一个更高效的代码,即我在下面实现的代码。 Is it possible to have a more efficient code, also using numpy?是否有可能有一个更有效的代码,也使用 numpy?

I am going to explain my algorithm and how it works.我将解释我的算法及其工作原理。 Considering the figure below, I have a matrix that contains 10000 matrix inside, and each matrix inside has a dimension 100x100.考虑下图,我有一个矩阵,里面包含 10000 个矩阵,里面的每个矩阵都有一个维度 100x100。 在此处输入图像描述

My output should be a matrix 100x100, like this:我的 output 应该是一个 100x100 的矩阵,如下所示:

输出

therefore, the first element of my "output" V[f(a_1,b_1)] is the variance of all f(a_1,b_1) elements contained in 10000 matrices.因此,我的“输出” V[f(a_1,b_1)]的第一个元素是 10000 个矩阵中包含的所有f(a_1,b_1)元素的方差。 Thus, I need to compute the variances of the elements with the same index.因此,我需要计算具有相同索引的元素的方差。

Below there is the code used, it should be correct (I hope..).下面是使用的代码,它应该是正确的(我希望..)。 is it possible to have a more efficient code?是否有可能有更高效的代码? (for simplicity, I simulate the input with random numbers, since the matrix is too big to post here) (为简单起见,我用随机数模拟输入,因为矩阵太大而无法在此处发布)

import numpy as np
input = np.random.randint(0, 100, size=(10000, 100, 100))
output = []
for n in range(100):
    row = []
    for i in range(100):
        row2 = [] 
        for m in range(10000):
            P_mi_sigmai = input[m][n][i]
            row2.append(P_mi_sigmai)
        variance = np.var(row2) 
        row.append(variance)
    output.append(row)
print(np.array(output).shape)

Here's how i would do it:这是我会怎么做:

output = input.var(axis = 0)

Here's a minimal reprex:这是一个最小的代表:

import numpy as np

arr = np.random.rand(5, 2, 2)
arr[:, 0, 0] = 1
var_arr = arr.var(0)


print(f'arr = \n{arr}')
print(f'var_arr = \n{var_arr}')

output: output:

arr = 
[[[1.         0.13682225]
  [0.24076008 0.61107865]]

 [[1.         0.99948733]
  [0.61871626 0.64518322]]

 [[1.         0.7979549 ]
  [0.53991881 0.17229415]]

 [[1.         0.13547922]
  [0.97390205 0.50778721]]

 [[1.         0.74116566]
  [0.05428085 0.86287107]]]
var_arr = 
[[0.         0.12837323]
 [0.10101842 0.05092759]]

I'm not gonna show it here, but using your code i get the same result我不会在这里展示它,但使用你的代码我得到相同的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM