Python 无法将输入数组从形状 (3,1) 广播到形状 (3,)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39824700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:45:58  来源:igfitidea点击:

Can't broadcast input array from shape (3,1) into shape (3,)

pythonnumpy

提问by Colin

import numpy as np

def qrhouse(A):
    (m,n) = A.shape
    R = A
    V = np.zeros((m,n))
    for k in range(0,min(m-1,n)):
        x = R[k:m,k]
        x.shape = (m-k,1)
        v = x + np.sin(x[0])*np.linalg.norm(x.T)*np.eye(m-k,1)
        V[k:m,k] = v
        R[k:m,k:n] = R[k:m,k:n]-(2*v)*(np.transpose(v)*R[k:m,k:n])/(np.transpose(v)*v)
    R = np.triu(R[0:n,0:n])     
    return V, R

A = np.array( [[1,1,2],[4,3,1],[1,6,6]] )
print qrhouse(A) 

It's qr factorization code, but I don't know why error happens. The value error happens in V[k:m,k] = v

这是 qr 分解代码,但我不知道为什么会发生错误。值错误发生在V[k:m,k] = v

value error :
could not broadcast input array from shape (3,1) into shape (3) 

回答by hpaulj

V[k:m,k] = v; vhas shape (3,1), but the target is (3,). k:mis a 3 term slice; kis a scalar.

V[k:m,k] = v; v具有形状 (3,1),但目标是 (3,)。k:m是 3 项切片;k是一个标量。

Try using v.ravel(). Or V[k:m,[k]].

尝试使用v.ravel(). 或者V[k:m,[k]]

But also understand why vhas its shape.

但也明白为什么v会有它的形状。

回答by Daniel Peterson

Another solution that would work is V[k:m,k:k+1] = v.

另一个可行的解决方案是V[k:m,k:k+1] = v.

k:k+1is a 1 term slice, making the target shape (3,1).

k:k+1是 1 项切片,使目标形状 (3,1)。

This seems like a better solution since you do not have to modify the input array.

这似乎是一个更好的解决方案,因为您不必修改输入数组。

回答by ChaosPredictor

Other way to do it is by transpose:

另一种方法是通过转置:

V[k:m,k] = v.transpose()