You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

前馈神经网络恐龙自玩游戏矩阵形状对齐错误解决求助

解决矩阵形状不匹配的ValueError问题

核心问题拆解

报错提示(1,4)与(10,4)无法对齐,说明你的current_layer.input是**(1,4)的二维数组,current_layer.weights是(10,4)**的二维数组。理论上np.dot((1,4), (4,10))(即weights.T的形状)是合法运算,问题大概率出在权重初始化逻辑或层间维度传递的错误上。

具体解决步骤

  • 修正权重初始化形状
    前馈神经网络中,输入层到隐藏层的权重形状应为(输入特征数, 隐藏层神经元数)。如果你的输入是4个特征、隐藏层有10个神经元,权重不能初始化为(10,4),要改成(4,10):

    # 错误初始化(示例)
    self.weights = np.random.randn(10, 4)
    # 正确初始化
    self.weights = np.random.randn(4, 10)
    

    此时直接用np.dot(current_layer.input, current_layer.weights)就能得到(1,10)的合法输出,无需转置。

  • 逐层核对维度传递
    在__feedforward方法中,每一层的输出要作为下一层的输入,打印每一步的维度确认衔接正确:

    def __feedforward(self, x):
        current_input = x
        for idx, layer in enumerate(self.layers):
            print(f"Layer {idx} input shape: {current_input.shape}")
            print(f"Layer {idx} weights shape: {layer.weights.shape}")
            layer_output = np.dot(current_input, layer.weights) + layer.bias
            current_input = self.activation(layer_output)
        return current_input
    

    一旦发现某层维度不匹配,直接修正对应层的权重形状。

  • 确认输入特征数一致性
    你在predict里加的x = np.array(x).reshape(1, -1)是正确的,但要确保原始输入确实是4个特征。可以在该行后加打印:

    print("Processed input shape:", x.shape)
    

    若输出不是(1,4),说明输入数据本身特征数不对,要回溯数据采集逻辑。

  • 检查多层网络的维度配置
    如果是多层网络,隐藏层到输出层的权重也要遵循(上一层神经元数, 当前层神经元数)的规则。比如隐藏层10个神经元、输出层2个动作(跳/不跳),权重应设为(10,2)。

内容的提问来源于stack exchange,提问作者FELIPE FERREIRA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 21:22:46