Numpy中np.dot运算矩阵与一维数组维度不匹配问题求助
Numpy np.dot() 形状不匹配问题解决
问题代码
import numpy as np X = [0.2, 0.1, 0.1, -0.9 ] weights = [[0.3, 0.4, 0.5], [-0.1, 0.9, -0.23], [0.05, -0.3, 0.7], [0.5, -0.123 , -0.008]] biases = 2 output = np.dot(weights, X) + biases print(output)
报错信息
output = np.dot(weights, X) + biases
File "<array_function internals>", line 200, in dot
ValueError: shapes (4,3) and (4,) not aligned: 3 (dim 1) != 4 (dim 0)
问题原因
你对weights的形状判断错误:
- 你认为
weights是(3,4),但实际Numpy会把4个长度为3的子列表解析为4行3列的矩阵,即shape=(4,3) X转成Numpy数组后是一维数组shape=(4,)np.dot的规则是:第一个参数的列数必须等于第二个参数的行数,这里3≠4,所以触发形状不匹配错误
解决方案
有两种可行的修改方式:
方式1:转置weights矩阵
将weights转置为(3,4),使其列数与X的行数匹配:
output = np.dot(np.array(weights).T, X) + biases
方式2:调换点乘顺序
直接用X点乘weights,此时X的行数(4)等于weights的行数(4),计算后得到长度为3的结果:
output = np.dot(X, weights) + biases
验证结果
两种方式运行后都会得到正确输出:
array([ 0.37 , 1.9037, -0.0772])
内容的提问来源于stack exchange,提问作者gops
相关产品推荐
相关产品推荐

