执行代码块后的迭代应该逐渐增加权重值,最后应该显示最后到达的权重。但是输出为所有迭代提供相同的权重。我是编码新手。我哪里错了?
所需的最终输出是 [[0],[0],[0],[0]] 和预期作为答案的权重是 [[-0.0405],[-0.0288],[-0.0066]]
功能代码块如下。
from numpy import *
import numpy as np
class pcn:
def __init__(self,inputs,targets):
if np.ndim(inputs)>1:
self.nIn=np.shape(inputs)[1]
else:
self.nIn=1
if np.ndim(targets)>1:
self.nOut=np.shape(targets)[1]
else:
self.nOut=1
self.nData=np.shape(inputs)[0]
self.weights=np.random.rand(self.nIn+1,self.nOut)*0.1-0.05
def pcntrain(self,inputs,targets,eta,nIterations):
inputs=np.concatenate((inputs,-np.ones((self.nData,1))),axis=1)
change = range(self.nData)
for n in range(nIterations):
self.activations=self.pcnfwd(inputs);
self.weights=eta*np.dot(np.transpose(inputs),self.activations-targets)
print('Iteration: {}'.format(n))
print (self.weights)
#activations=self.pcnfwd(inputs)
print('Final outputs are : {}'.format(activations))
# return self.weights
def pcnfwd(self,inputs):
activations=np.dot(inputs,self.weights)
return np.where(activations>0,1,0)
输入代码语句是
inputs=inputs = np.array([[0,0],[0,1],[1,0],[1,1]])
targets=np.array([[0],[1],[1],[0]]) # XOR Targets
主要代码块是
p=pcn(inputs,targets)
p.pcntrain(inputs,targets,0.25,15)
截至目前的代码输出需要随着权重的逐渐变化进行更正,直到最终迭代。
Iteration: 0
[[ 0.25]
[ 0. ]
[-0.25]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 1
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 2
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 3
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 4
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 5
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 6
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 7
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 8
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 9
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 10
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 11
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 12
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 13
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]
Iteration: 14
[[ 0.25]
[ 0.25]
[-0.5 ]]
Final outputs are : [[1 1]
[1 1]]