我一直试图让以下神经网络充当一个简单的AND门,但它似乎没有起作用。以下是我的代码:
import numpy as np
def sigmoid(x,derivative=False):
if(derivative==True):
return x*(1-x)
return 1/(1+np.exp(-x))
np.random.seed(1)
weights = np.array([0,0,0])
training = np.array([[[1,1,1],1],
[[1,1,0],0],
[[1,0,1],0],
[[1,0,0],0]])
for iter in xrange(training.shape[0]):
#forwardPropagation:
a_layer1 = training[iter][0]
z_layer2 = np.dot(weights,a_layer1)
a_layer2 = sigmoid(z_layer2)
hypothesis_theta = a_layer2
#backPropagation:
delta_neuron1_layer2 = a_layer2 - training[iter][1]
Delta_neuron1_layer2 = np.dot(a_layer2,delta_neuron1_layer2)
update = Delta_neuron1_layer2/training.shape[0]
weights = weights-update
x = np.array([1,0,1])
print weights
print sigmoid(np.dot(weights,x))
上面的程序将奇怪的值作为输出返回,输入X的返回值高于数组[1,1,1]。每个训练/测试“输入”的第一个元素代表偏置单元。该代码基于Andrew Ng关于机器学习Coursera课程的视频:https://www.coursera.org/learn/machine-learning
提前感谢您的协助。
答案 0 :(得分:1)
一些指示:
我已经改造了你的阵列,也增加了你的输入。
<section class="center slider">
<div>
<img src="http://placehold.it/300x200?text=click%20me">
<div id="iframe"><img src="http://placehold.it/600x400?text=your%20iframe"><span id="exit">X</span></div>
</div>
</section>
输出:
import numpy as np
def sigmoid(x,derivative=False):
if(derivative==True):
return x*(1-x)
return 1/(1+np.exp(-x))
np.random.seed(1)
weights = np.random.randn(1, 3)
training = np.array([[np.array([0, 0, 0]).reshape(1, -1), 1],
[np.array([0,0,1]).reshape(1, -1), 0],
[np.array([0,1,0]).reshape(1, -1), 0],
[np.array([0,1,1]).reshape(1, -1), 0],
[np.array([1, 0, 0]).reshape(1, -1), 1],
[np.array([1,0, 1]).reshape(1, -1), 0],
[np.array([1,1,0]).reshape(1, -1), 0],
[np.array([1,1,1]).reshape(1, -1), 1],
])
for iter in xrange(training.shape[0]):
#forwardPropagation:
a_layer1 = training[iter][0]
z_layer2 = np.dot(weights,a_layer1.reshape(-1, 1))
a_layer2 = sigmoid(z_layer2)
hypothesis_theta = a_layer2
#backPropagation:
delta_neuron1_layer2 = (a_layer2 - training[iter][1] ) * sigmoid(a_layer2 , derivative=True)
Delta_neuron1_layer2 = np.dot(delta_neuron1_layer2 , a_layer1)
update = Delta_neuron1_layer2
weights = weights - update
x = np.array([0,0, 1])
print sigmoid(np.dot(weights,x.reshape(-1, 1)))
x = np.array([0,1,1])
print sigmoid(np.dot(weights,x.reshape(-1, 1)))
x = np.array([1,1,1])
print sigmoid(np.dot(weights,x.reshape(-1, 1)))
它不干净,而且肯定有改进的余地。但至少,你现在有了一些东西。预期产生理论0的输入比产生理论值1的输入更接近0。