繁体   English   中英

“ValueError:matmul:输入操作数 1 在其核心维度 0 中存在不匹配……(大小 2 与 1 不同)”

[英]“ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0 … (size 2 is different from 1)”

我刚刚开始学习 Python/NumPy。 我想编写一个函数,该函数将应用具有 2 个输入和 1 个输出以及给定权重矩阵的操作,即两个形状为 (2,1) 的 NumPy 数组,并且应该使用 tanh 返回一个形状为 (1,1) 的 NumPy 数组。 这是我想出的:

import numpy as np
def test_neural(inputs,weights):
    result=np.matmul(inputs,weights)
    print(result)
    z = np.tanh(result)
    return (z)
x = np.array([[1],[1]])
y = np.array([[1],[1]])

z=test_neural(x,y)
print("final result:",z)

但我收到以下 matmul 错误:

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 1)

有人可以告诉我我缺少什么吗?

问题是矩阵乘法的维度。

您可以将矩阵与这样的共享维度相乘( 在此处阅读更多内容):

(M , N) * (N , K) => Result dimensions is (M, K)

你尝试乘法:

(2 , 1) * (2, 1)

但是尺寸是非法的。

所以你必须在乘法之前转置inputs (只需在矩阵上应用.T ),这样你就可以得到有效的乘法维度:

(1, 2) * (2, 1) => Result dimension is (1, 1)

代码:

import numpy as np
def test_neural(inputs,weights):
    result=np.matmul(inputs.T, weights)
    print(result)
    z = np.tanh(result)
    return (z)
x = np.array([[1],[1]])
y = np.array([[1],[1]])

z=test_neural(x,y)

# final result: [[0.96402758]]
print("final result:",z)

暂无
暂无

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

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