python - 从错误的 numpy 形状中 reshape 函数广播

标签 python numpy spyder reshape

我正在尝试将 numpy.array 从形状 (4,4) reshape 为形状 (2,2,2,2)。我收到的错误是:

ValueError:无法将输入数组从形状 (2,2,2,2) 广播到形状 (4,4)。

这让我觉得我的形状是倒退的,但检查后发现事实并非如此。

我有一个用户定义的函数,它使用 np.reshape 将数组 reshape 为特定形状(如果它还不是该形状)。我尝试消除用户定义的函数并仅使用 np.reshape,但它返回了相同的错误。我错过了什么?

reshape 函数:

def reshape(matrix, ports, modes):
    shape = (ports, ports, modes, modes)
    if(np.shape(matrix) != shape): #reshape if necessary
        return np.reshape(matrix, shape)
    else:
        return matrix

我在哪里调用这个函数:


def plot(S, F, ports, modes, x_range, y_range, title, f_units, 
         multi_modal = True):
    data = {} #create dictionary to store S-parameters
    if(not multi_modal): #if we want average
        for f in range(0, len(F)): #iterate through frequencies
            print(np.shape(S[f]))
            S[f] = reshape(S[f], ports, modes)

在本例中,端口 = 2,模式 = 2。

S[f] 是形状为 (4,4) 的 np.array:

[[ 1.00000000e+00+0.00000000e+00j -1.02728868e-19+1.64952184e-22j
  -1.37762998e-20+2.40441793e-24j -4.18063430e-24-1.18287261e-21j]
 [ 0.00000000e+00-0.00000000e+00j -1.00000000e+00+1.22464680e-16j
   3.03393173e-26-1.77961140e-24j  1.57277027e-25+2.06062998e-23j]
 [-1.95100984e-27+3.66506948e-24j  2.38762635e-25+1.48052807e-22j
   1.00000000e+00+0.00000000e+00j  2.90518731e-20+1.33913685e-17j]
 [-3.47614015e-25-4.08540212e-23j -3.30653510e-21+2.87402660e-23j
   1.77338192e-21+2.27000073e-19j -1.00000000e+00+1.22464680e-16j]]

为什么返回错误:

ValueError: could not broadcast input array from shape (2,2,2,2) into shape (4,4)

什么时候应该将其从 (4,4) reshape 为 (2,2,2,2)?

最佳答案

这样就可以了

def plot(S, F, ports, modes, x_range, y_range, title, f_units, 
         multi_modal = True):
    data = {} #create dictionary to store S-parameters
    if(not multi_modal): #if we want average
        for f in range(0, len(F)): #iterate through frequencies
            print(np.shape(S[f]))
            S_reshaped = reshape(S[f], ports, modes)

如果您需要存储结果,您可以创建一个空列表,然后将重构后的数组附加到其中。

def plot(S, F, ports, modes, x_range, y_range, title, f_units, 
         multi_modal = True):
    data = {} #create dictionary to store S-parameters
    S_reshaped=[]
    if(not multi_modal): #if we want average
        for f in range(0, len(F)): #iterate through frequencies
            print(np.shape(S[f]))
            S_reshaped.append(reshape(S[f], ports, modes))

关于python - 从错误的 numpy 形状中 reshape 函数广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55593784/

相关文章:

python - 如何配置 hive.Connection() 以将我想要的设置传递给 Hive?

python - 如何在完成代码的同时进行 pandas 列选择?

python numpy.convolve 解决卷积积分的限制从 0 到 t 而不是 -t 到 t

python - python 日志记录如何获取它的配置

java - 将 NumPy 和 Cpython 与 Jython 一起使用

python - 生成仅填充值 0 或 1 的随机稀疏矩阵

python - 为什么当我点击 Dictionary 变量时 Spyder 不能打开它?

python - 如何在spyder中添加python控制台

python - 使用 python 将文本拆分并保存在文件中

python - 从 DataFrame 列中提取特定字符/文本