所以我正在尝试实现(a * b)*(M * a.T),但我一直收到ValueError。由于我是python和numpy函数的新手,因此帮助非常好。提前致谢。
import numpy.matlib
import numpy as np
def complicated_matrix_function(M, a, b):
ans1 = np.dot(a, b)
ans2 = np.dot(M, a.T)
out = np.dot(ans1, ans2)
return out
M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
a = np.array([[1, 1, 0]])
b = np.array([[-1], [2], [5]])
ans = complicated_matrix_function(M, a, b)
print(ans)
print()
print("The size is: ", ans.shape)
错误消息是:
ValueError:形状(1,1)和(4,1)不对齐:1(dim 1)!= 4(dim 0)
答案 0 :(得分:1)
该错误消息告诉您numpy.dot
不知道如何处理(1x1)矩阵和(4x1)矩阵。但是,由于在您的公式中您只想说要相乘,所以我假设您只想将标量乘以标量乘积(a,b)乘以与矩阵向量乘积(嘛)。为此,您只需在python中使用*
。
因此,您的示例将是:
import numpy.matlib
import numpy as np
def complicated_matrix_function(M, a, b):
ans1 = np.dot(a, b)
ans2 = np.dot(M, a.T)
out = ans1 * ans2
return out
M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
a = np.array([[1, 1, 0]])
b = np.array([[-1], [2], [5]])
ans = complicated_matrix_function(M, a, b)
print(ans)
print()
print("The size is: ", ans.shape)
导致
[[ 3]
[ 9]
[15]
[21]]
The size is: (4, 1)
注意
请注意,numpy.dot
会做很多interpretation
来找出您想做什么。因此,如果您不需要结果大小为(4,1),则可以将所有内容简化为:
import numpy.matlib
import numpy as np
def complicated_matrix_function(M, a, b):
ans1 = np.dot(a, b)
ans2 = np.dot(M, a) # no transpose required
out = ans1 * ans2
return out
M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
a = np.array([1, 1, 0]) # no extra [] required
b = np.array([-1, 2, 5]) # no extra [] required
ans = complicated_matrix_function(M, a, b)
print(ans)
print()
print("The size is: ", ans.shape)
导致
[ 3 9 15 21]
The size is: (4,)