我正在嘗試實現一個簡單的神經網絡。我想打印最初的圖案,重量,激活。然後,我希望它能夠打印學習過程(即學習時所經歷的每種模式)。我仍然無法做到這一點 - 它返回最初和最後的模式(當我把印刷品放在適當的位置),但沒有別的。提示和技巧讚賞 - 我是一個Python的完全新手!無法使用def函數在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]
有一點需要檢查的是Python的PEP-8編碼標準。通常,每個人都使用4個空格來縮進python代碼以及其他一些約定: http://www.python.org/dev/peps/pep-0008/ 快速總結此處 http:// wwd。 ca/blog/2009/07/09/pep-8-cheatsheet/ – mcpeterson 2010-10-18 18:57:09