【发布时间】:2019-03-28 14:33:43
【问题描述】:
我正在实现一个多类神经网络,它将识别输入图像中的数字。输入图像是五乘五像素,显示五个数字。因此,神经网络模型包含 25 个输入节点。 4 个输出节点(因为我们必须对 5 个输出进行分类)和 50 个隐藏节点。我使用 sigmoid 函数作为隐藏节点的激活函数,使用 softmax 函数作为输出节点的激活函数。
我的输入参数 X 包含堆叠的二维图像数据,即 5*5*5 三维矩阵。因此,我使用 np.reshape(X[:,:,x],25) 将其转换为 (25,) 向量,以便我可以轻松获得加权和(因为权重为 25 *50 用于隐藏节点的输入,50*5 用于隐藏到输出节点)。
我面临的问题是,当我分别计算输入到隐藏和隐藏到输出的 Delta 时,我有值错误 "ValueError: shape (50,) and (5,5) not aligned: 50 (dim 0) != 5 (dim 0)" 我完全理解是因为两个数组的尺寸。但是我无法弄清楚解决方案,以便我可以以某种方式重塑它们并采用点积。由于我是第一次学习 python 和这种神经网络的东西并编写自己的代码,所以我在玩矩阵方面没有太多专业知识。我需要一些帮助 1) 解决这个问题,2) 我怎样才能改进这个网络(未来的实践)。 3)如何使网络通用,以便如果我可以添加更多层等,我不会弄乱不同维度的矩阵乘法?代码原型如下。
代码
# other stuff
def function(W1, W2, X, D):
N = 5
for x in range(N):
# reshaping input in 25*1 vector
l0 = np.reshape(X[:,:,x],25)
ll = sigmoid(np.dot(l0,W1))
l2 = softmax(np.dot(ll,W2))
l2_error = D - l2
l2_delta = l2_error
l1_error = l2_delta.dot(W2.T)
l1_delta = ll*(1-ll)*l1_error
DW2 = alpha*ll.T.dot(l2_delta) #ValueError: shapes (50,) and (5,5) not aligned: 50 (dim 0) != 5 (dim 0)
W2 = W2 + DW2
DW1 = alpha*l0.T.dot(l1_delta) #ValueError: shapes (25,) and (5,50) not aligned: 25 (dim 0) != 5 (dim 0)
W1 = W1 + DW1
# other stuff
X = np.zeros((5,5,5), dtype=int)
D = np.zeros((5,5), dtype=int)
X[:,:,0] = [[0 ,1, 1, 0, 0],
[0 ,0, 1, 0, 0],
[0 ,0, 1, 0, 0],
[0 ,0, 1, 0, 0],
[0 ,1, 1, 1, 0]]
X[:,:,1] = [[1 ,1, 1, 1, 0],
[0 ,0, 0, 0, 1],
[0 ,1, 1, 1, 0],
[1 ,0, 0, 0, 0],
[1 ,1, 1, 1, 1]]
X[:,:,2] = [[1 ,1, 1, 1, 0],
[0 ,0, 0, 0, 1],
[0 ,1, 1, 1, 0],
[0 ,0, 0, 0, 1],
[1 ,1, 1, 1, 0]]
X[:,:,3] = [[0 ,0, 0, 1, 0],
[0 ,0, 1, 1, 0],
[0 ,1, 0, 1, 0],
[1 ,1, 1, 1, 1],
[0 ,0, 0, 1, 0]]
X[:,:,4] = [[1 ,1, 1, 1, 1],
[1 ,0, 0, 0, 0],
[1, 1, 1, 1, 0],
[0 ,0, 0, 0, 1],
[1 ,1, 1, 1, 0]]
D = np.array([ [1,0,0,0,0],[0,1,0,0,0],[0,0,1,0,0],[0,0,0,1,0],[0,0,0,0,1] ]).T
W1 = 2*np.random.random((25,50)) - 1
W2 = 2*np.random.random((50,5)) - 1
W1, W2 = Multiclass(W1, W2, X, D)
【问题讨论】:
标签: python neural-network classification matrix-multiplication