在此代码中
import random
import numpy as np
class Network(object):
def __init__(self, sizes):
"""The list ``sizes`` contains the number of neurons in the
respective layers of the network. For example, if the list
was [2, 3, 1] then it would be a three-layer network, with the
first layer containing 2 neurons, the second layer 3 neurons,
and the third layer 1 neuron. The biases and weights for the
network are initialized randomly, using a Gaussian
distribution with mean 0, and variance 1. Note that the first
layer is assumed to be an input layer, and by convention we
won't set any biases for those neurons, since biases are only
ever used in computing the outputs from later layers."""
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
self.weights = [np.random.randn(y, x)
for x, y in zip(sizes[:-1], sizes[1:])]
def feedforward(self, a):
"""Return the output of the network if ``a`` is input."""
for b, w in zip(self.biases, self.weights):
a = sigmoid(np.dot(w, a)+b)
return a
NN=Network([3,2,1])
我不明白:
self.biases = [np.random.randn(y,1)表示y的大小[1:]]
如果NN.sizes [1:]为[2,1],那么y是什么?
下一行相同
self.weights = [np.random.randn(y,x) 用于zip中的x,y(尺寸[:-1],尺寸[1:])]
我既不了解x,也不了解zip的工作原理
答案 0 :(得分:2)
在此代码中,他们正在使用列表comprehensions。代码
[np.random.randn(y, 1) for y in sizes[1:]]
等同于
self.biases=[]
for y in sizes[1:]:
self.biases.append(np.random.randn(y,1))
行大小[1:]用于从第一个索引获取列表值,即不包括list的第一个元素。例如,
a=[5,6,7,8]
print(a[1:])
将输出作为[6,7,8]
另外,如果您提供print(a[:-1])
,我们将获得输出为[5,6,7]
现在,对于下一行,
self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])]
使用for循环的等效代码是
self.weights=[]
for (x,y) in zip(sizes[:-1],sizes[1:]):
self.weights.append(n.random.randn(y,x))
Zip只是映射两个列表,并允许您同时遍历两个列表。在这种情况下,sizes [:-1],不包括最后一个元素的列表大小,sizes [1:],不包括第一个元素的列表大小。 例如,如果您有两个列表,则需要按如下所示打印它们:
a=[1,2,3,4]
b=['a','b','c','d']
p=list(zip(a,b))
print (p)
会给您
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
现在,如果您必须打印每个元素:
for k,v in zip(a,b):
print (k,v)
将为您提供输出
1 a
2 b
3 c
4 d
希望你很清楚!