我一直在尝试在numpy中编写一个2层NN。在它上面,我发现了矩阵w0在进入循环时如何改变形状的奇怪行为。w0
的形状是(3,1)
,X
的形状是(4,3)
。结果必须是(4,1)
,但当程序进入循环时,w0
变为(4,4)
。在循环之外,它工作得很好。同样,当我使用np.dot(X,w0)
时会发生这种情况,但当我使用np.dot(w0.T,X.T)
时效果很好。代码如下:
def sigmoid(x, deriv=False):
if deriv == True:
return x*(1-x)
return 1/(1+np.exp(-x))
X = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
y = np.array([0,0,1,1]).T
w0 = np.random.normal(0,0.1,(3,1))
w0.shape
for iter in range(10000):
#forward propagation
#l0 = X
multiply = np.dot(X,w0)
if iter == 1: print(multiply.shape)
l1 = sigmoid(multiply)
if iter == 1:
print(w0)
print(multiply.shape)
print(X.shape)
print(w0.shape)
print(l1.shape)
#Calculating error:
error = y-l1
if iter == 1: print(error.shape)
#Backpropagating for update
d_l1 = error*sigmoid(l1, True)
if iter == 1: print(d_l1.shape)
#Update weights : Shape -- (4*3).T * (4*1) = (3*1)
w0 = w0 + np.dot(np.transpose(X), d_l1.T)
print ('Results after training:')
print (l1)
目前没有回答
相关问题 更多 >
编程相关推荐