我正在尝试实现一个简单的神经网络。我想打印初始模式、权重、激活。然后我希望它打印学习过程(即它在学习时经历的每个模式)。我还不能这样做——它返回初始和最终模式(当我把 print p 放在适当的地方时),但没有别的。提示和技巧表示赞赏 - 我是 Python 的新手!
#!/usr/bin/python
import random
p = [ [1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1] ] # pattern I want the net to learn
n = 5
alpha = 0.01
activation = [] # unit activations
weights = [] # weights
output = [] # output
def initWeights(n): # set weights to zero, n is the number of units
global weights
weights = [[[0]*n]*n] # initialised to zero
def initNetwork(p): # initialises units to activation
global activation
activation = p
def updateNetwork(k): # pick unit at random and update k times
for l in range(k):
unit = random.randint(0,n-1)
activation[unit] = 0
for i in range(n):
activation[unit] += output[i] * weights[unit][i]
output[unit] = 1 if activation[unit] > 0 else -1
def learn(p):
for i in range(n):
for j in range(n):
weights += alpha * p[i] * p[j]
最佳答案
你的线路有问题:
weights = [[[0]*n]*n]
当您使用*
时,您会乘以对象引用。您每次都使用相同的 n-len 零数组。这将导致:
>>> weights[0][1][0] = 8
>>> weights
[[[8, 0, 0], [8, 0, 0], [8, 0, 0]]]
所有子列表的第一项是8,因为它们是同一个列表。您多次存储同一个引用,因此修改其中任何一个的第 n 个项目都会改变所有这些。
关于python - 使用 def 函数时无法在 Python 中打印变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3962163/