简体   繁体   English

为什么 numpy.dot() 会抛出 ValueError: shapes not aligned?

[英]Why is numpy.dot() throwing a ValueError: shapes not aligned?

I want to write a program that finds the eigenvectors and eigenvalues of a Hermitian matrix by iterating over a guess (Rayleigh quotient iteration).我想编写一个程序,通过迭代猜测(Rayleigh 商迭代)找到 Hermitian 矩阵的特征向量和特征值。 I have a test matrix that I know the eigenvectors and eigenvalues of, however when I run my code I receive我有一个测试矩阵,我知道它的特征向量和特征值,但是当我运行我的代码时,我收到

ValueError: shapes (3,1) and (3,1) not aligned: 1 (dim 1) != 3 (dim 0) ValueError:形状 (3,1) 和 (3,1) 未对齐:1 (dim 1) != 3 (dim 0)

By splitting each numerator and denominator into separate variables I've traced the problem to the line:通过将每个分子和分母拆分为单独的变量,我将问题追溯到以下行:

nm=np.dot(np.conj(b1),np.dot(A,b1))

My code:我的代码:

import numpy as np
import numpy.linalg as npl

def eigen(A,mu,b,err):

    mu0=mu
    mu1=mu+10*err

    while mu1-mu > err:

        n=np.dot((npl.inv(A-mu*np.identity(np.shape(A)[0]))),b)
        d=npl.norm(np.dot((npl.inv(A-(mu*np.identity(np.shape(A)[0])))),b))

        b1=n/d
        b=b1

        nm=np.dot(np.conj(b1),np.dot(A,b1))
        dm=np.dot(np.conj(b1),b1)

        mu1=nm/dm
        mu=mu1

    return(mu,b)

A=np.array([[1,2,3],[1,2,1],[3,2,1]])
mu=4
b=np.array([[1],[2],[1]])
err=0.1

eigen(A,mu,b,err) 

I believe the dimensions of the variables being input into the np.dot() function are wrong, but I cannot find where.我相信输入到np.dot()函数中的变量的维度是错误的,但我找不到位置。 Everything is split up and renamed as part of my debugging, I know it looks very difficult to read.作为我调试的一部分,所有内容都被拆分并重命名,我知道它看起来很难阅读。

The mathematical issue is with matrix multiplication of shapes (3,1) and (3,1).数学问题是形状 (3,1) 和 (3,1) 的矩阵乘法。 That's essentially two vectors.这本质上是两个向量。 Maybe you wanted to use the transposed matrix to do this?也许您想使用转置矩阵来做到这一点?

nm = np.dot(np.conj(b1).T, np.dot(A, b1))
dm = np.dot(np.conj(b1).T, b1)

Have a look at the documentation of np.dot to see what arguments are acceptable.查看np.dot的文档,了解可接受的参数。

If both a and b are 1-D arrays, it is inner product of vectors (...)如果 a 和 b 都是一维数组,则它是向量的内积 (...)

If both a and b are 2-D arrays, it is matrix multiplication (...)如果a和b都是二维数组,就是矩阵乘法(...)

The variables you're using are of shape (3, 1) and therefore 2-D arrays.您使用的变量是 (3, 1) 形状的,因此是二维数组。

Also, this means, alternatively, instead of transposing the first matrix, you could use a flattened view of the array.此外,这意味着,或者,您可以使用数组的展平视图,而不是转置第一个矩阵。 This way, it's shape (3,) and a 1-D array and you'll get the inner product:这样,它是形状 (3,) 和一维数组,您将获得内积:

nm = np.dot(np.conj(b1).ravel(), np.dot(A, b1).ravel())
dm = np.dot(np.conj(b1).ravel(), b1.ravel())

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

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