在做Python矩阵相乘的时候
有一个矩阵x=[3.5 5.1]
一个矩阵y=[-1.]
做矩阵相乘np.dot(y,x)
报错:
shape(1,)and shape(2,)not aligned :1 (dim 0)!=2(dim 0)
请问是什么问题呢?

Python编程矩阵相乘问题
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- ChatGPTᴼᴾᴱᴺᴬᴵ 2023-03-22 01:05关注
该回答引用NewBing
你好,这是Bing。😊
这个问题可能是因为你的矩阵x和y的形状不匹配。矩阵乘法要求第一个矩阵的列数等于第二个矩阵的行数,但是你的x有2列,而y只有1行①。
你可以尝试把y转置成一个2维矩阵,或者用np.array而不是np.matrix来创建x和y①。
源: 与必应的对话, 2023/3/22
(1) python - Numpy matrix multiplication fails ("shapes not aligned") when .... https://stackoverflow.com/questions/52368146/numpy-matrix-multiplication-fails-shapes-not-aligned-when-second-element-is 访问时间 2023/3/22.
(2) python 3.x - Why I am getting matrices are not aligned error for .... https://stackoverflow.com/questions/60726146/why-i-am-getting-matrices-are-not-aligned-error-for-dataframe-dot-function 访问时间 2023/3/22.
(3) neural network - Matrix multiplication issue (shapes not alligned .... https://datascience.stackexchange.com/questions/37152/matrix-multiplication-issue-shapes-not-alligned 访问时间 2023/3/22.
我:还有其他可能导致这个错误的原因吗?
有可能。如果你用pandas的对象做矩阵乘法,也可能会出现这个错误。这是因为pandas会根据索引来对齐数据,而不是根据形状①。你可以在做矩阵乘法之前,把pandas对象转换成numpy数组①。
还有一种情况是,如果你用np.dot来做矩阵乘法,而不是用@运算符或者np.matmul函数,也可能会出现这个错误。这是因为np.dot在处理高维数组时,会按照最后两个轴来做乘法,而不是按照标准的矩阵乘法规则②。你可以用@运算符或者np.matmul函数来避免这个问题②。
源: 与必应的对话, 2023/3/22
(1) Error: not aligned matrix multiplication in Python - Stack Overflow. https://stackoverflow.com/questions/66165387/error-not-aligned-matrix-multiplication-in-python 访问时间 2023/3/22.
(2) neural network - Matrix multiplication issue (shapes not alligned .... https://datascience.stackexchange.com/questions/37152/matrix-multiplication-issue-shapes-not-alligned 访问时间 2023/3/22.
(3) [pandas matrix multiplication] ValueError: matrices are not aligned. https://cumsum.wordpress.com/2022/12/04/pandas-matrix-multiplicationvalueerror-matrices-are-not-aligned/ 访问时间 2023/3/22.
(4) Numpy matrix multiplication fails ("shapes not aligned") when second .... https://stackoverflow.com/questions/52368146/numpy-matrix-multiplication-fails-shapes-not-aligned-when-second-element-is 访问时间 2023/3/22.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用