[英]Creating a Neural Network to determine an XOR gate
I am trying to create aa simple neural network that determines an XOR gate in Python for my class assignment, but I keep getting an error.我正在尝试创建一个简单的神经网络,用于在 Python 中为我的课程分配确定 XOR 门,但我一直收到错误消息。 Below is my code and corresponding error:下面是我的代码和相应的错误:
logic_inputs = np.array(logic_inputs)
logic_inputs
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)
W1 = np.array([[20],
[20]])
b1 = np.array([[-30]])
W2 = np.array([[-20],
[-20]])
b2 = np.array([[10]])
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(X)
np.round(xor_output)
Error错误
ValueError Traceback (most recent call last)
<ipython-input-83-84793a680685> in <module>
40 xor_gate = Network(hidden_layer, output_layer)
41
---> 42 xor_output = xor_gate.activate(X)
43 np.round(xor_output)
<ipython-input-83-84793a680685> in activate(self, X)
36 z = self.hidden.activate(X)
37
---> 38 return self.output.activate(z)
39
40 xor_gate = Network(hidden_layer, output_layer)
<ipython-input-83-84793a680685> in activate(self, X)
11
12 def activate(self, X):
---> 13 z = np.dot(X, self.W) + self.b
14 return sigmoid(z)
15
<__array_function__ internals> in dot(*args, **kwargs)
ValueError: shapes (4,1) and (2,1) not aligned: 1 (dim 1) != 2 (dim 0)
You are trying to calculate dot product between two matrices with shapes (4,1) and (2,1) which is not possible.您正在尝试计算形状为 (4,1) 和 (2,1) 的两个矩阵之间的点积,这是不可能的。 Dot product can only be calculated if shape of matrices are following: (a, n), (n, b) which yields a matrix of shape (a, b).只有当矩阵的形状如下时才能计算点积: (a, n), (n, b) 产生形状为 (a, b) 的矩阵。 You should initialize your weights to be of shape (1, 2)您应该将权重初始化为形状 (1, 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.