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

神经网络实现XOR门遇维度不匹配报错,请求技术帮助

用神经网络实现XOR门的报错解决方案

问题描述

OR层代码运行正常:

import numpy as np

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

W = np.array([[20],
              [20]])

class Layer():

  def __init__(self, W, b):
    self.m = W.shape[0]
    self.n = W.shape[1]
    self.W = W
    self.b = b

  def activate(self, X):
    z = np.dot(X, self.W) + self.b
    return sigmoid(z)

OR_layer = Layer(W, -10)
# XOR测试输入
logic_inputs = np.array([[0,0], [0,1], [1,0], [1,1]])
print(np.round(OR_layer.activate(logic_inputs)))

输出符合预期:

array([[0.],
       [1.],
       [1.],
       [1.]])

但实现XOR网络时出现报错:Shapes (4,1) and (2,1) not aligned: 1 (dim 1) != 2 (dim 0),相关代码如下:

W1 = np.array([[-20],[-20]])
b1 = np.array(30)

W2 = np.array([[20],[20]])
b2 = np.array(-30)

hidden_layer = Layer(W1, b1)
output_layer = Layer(W2, b2)

class Network():

  def __init__(self, hidden, output):
    self.hidden = hidden
    self.output = output

  def activate(self, X):
    z = self.hidden.activate(X)
    return self.output.activate(z)

xor_gate = Network(hidden_layer, output_layer)

xor_output = xor_gate.activate(logic_inputs)#throwing error
np.round(xor_output)

期望输出应为:

array([[0.],
       [1.],
       [1.],
       [0.]])

错误原因

报错的核心是矩阵维度不匹配:

  • 隐藏层的权重W1形状是(2,1),当输入logic_inputs(形状(4,2))经过np.dot(X, W1)后,输出形状是(4,1)。
  • 输出层的权重W2形状是(2,1),此时用(4,1)的隐藏层输出和(2,1)的W2做矩阵乘法,第一个矩阵的列数(1)不等于第二个矩阵的行数(2),导致维度不匹配报错。

XOR需要隐藏层包含2个神经元,这样隐藏层输出形状才能和输出层权重匹配。

修复后的代码

调整隐藏层和输出层的权重、偏置维度,确保矩阵乘法维度兼容:

import numpy as np

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

class Layer():
    def __init__(self, W, b):
        self.W = W
        self.b = b

    def activate(self, X):
        z = np.dot(X, self.W) + self.b
        return sigmoid(z)

class Network():
    def __init__(self, hidden, output):
        self.hidden = hidden
        self.output = output

    def activate(self, X):
        hidden_out = self.hidden.activate(X)
        return self.output.activate(hidden_out)

# 定义XOR网络的权重和偏置
# 隐藏层:2个神经元,权重形状(2,2),偏置形状(2,)
W1 = np.array([[20, -20], [20, -20]])
b1 = np.array([-10, 30])

# 输出层:1个神经元,权重形状(2,1),偏置形状(1,)
W2 = np.array([[20], [20]])
b2 = np.array([-30])

# 初始化网络
hidden_layer = Layer(W1, b1)
output_layer = Layer(W2, b2)
xor_gate = Network(hidden_layer, output_layer)

# 测试输入
logic_inputs = np.array([[0,0], [0,1], [1,0], [1,1]])
xor_output = xor_gate.activate(logic_inputs)
print(np.round(xor_output))

运行结果

输出符合预期:

array([[0.],
       [1.],
       [1.],
       [0.]])

内容的提问来源于stack exchange,提问作者Aman Narsu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:15:09