没有合适的资源?快使用搜索试试~ 我知道了~
首页详解python实现识别手写MNIST数字集的程序
我们需要做的第⼀件事情是获取 MNIST 数据。如果你是⼀个 git ⽤⼾,那么你能够通过克隆这本书的代码仓库获得数据,实现我们的⽹络来分类数字 git clone https://github.com/mnielsen/neural-networks-and-deep-learning.git class Network(object): def __init__(self, sizes): self.num_layers = len(sizes) self.sizes = sizes self.biases = [np.random.randn(y, 1) for y in size
资源详情
资源评论
资源推荐

详解详解python实现识别手写实现识别手写MNIST数字集的程序数字集的程序
我们需要做的第件事情是获取 MNIST 数据。如果你是个 git ,那么你能够通过克隆这本书的代码仓库获得数据,实现我们
的络来分类数字
git clone https://github.com/mnielsen/neural-networks-and-deep-learning.git
class Network(object):
def __init__(self, sizes):
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:])]
在这段代码中,列表 sizes 包含各层神经元的数量。例如,如果我们想创建个在第层有2 个神经元,第层有 3 个神经元,最
后层有 1 个神经元的 Network 对象,我们应这样写代码:
net = Network([2, 3, 1])
Network 对象中的偏置和权重都是被随机初始化的,使 Numpy 的 np.random.randn 函数来成均值为 0,标准差为 1 的斯分
布。这样的随机初始化给了我们的随机梯度下降算法个起点。在后的章节中我们将会发现更好的初始化权重和偏置的法,但
是前随机地将其初始化。注意 Network 初始化代码假设第层神经元是个输层,并对这些神经元不设置任何偏置,因为偏置
仅在后的层中于计算输出。有了这些,很容易写出从个 Network 实例计算输出的代码。我们从定义 S 型函数开始:
def sigmoid(z):
return 1.0/(1.0+np.exp(-z))
注意,当输 z 是个向量或者 Numpy 数组时,Numpy 动地按元素应 sigmoid 函数,即以向量形式。
我们然后对 Network 类添加个 feedforward 法,对于络给定个输 a,返回对应的输出 6 。这个法所做的是对每层应程
(22):
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
当然,我们想要 Network 对象做的主要事情是学习。为此我们给它们个实现随即梯度下降算法的 SGD 法。代码如下。其中
些地看似有点神秘,我会在代码后逐个分析
def SGD(self, training_data, epochs, mini_batch_size, eta,
test_data=None):
"""Train the neural network using mini-batch stochastic
gradient descent. The "training_data" is a list of tuples
"(x, y)" representing the training inputs and the desired
outputs. The other non-optional parameters are
self-explanatory. If "test_data" is provided then the
network will be evaluated against the test data after each
epoch, and partial progress printed out. This is useful for
tracking progress, but slows things down substantially."""
if test_data: n_test = len(test_data)
n = len(training_data)
for j in xrange(epochs):
random.shuffle(training_data)
mini_batches = [
training_data[k:k+mini_batch_size] for k in xrange(0, n, mini_batch_size)] for mini_batch in mini_batches:
self.update_mini_batch(mini_batch, eta)
if test_data:
print "Epoch {0}: {1} / {2}".format(
j, self.evaluate(test_data), n_test)
else:
print "Epoch {0} complete".format(j)
training_data 是个 (x, y) 元组的列表,表训练输和其对应的期望输出。变量 epochs 和mini_batch_size 正如你预料的——迭
代期数量,和采样时的批量数据的。 eta 是学习速率,η。如果给出了可选参数 test_data ,那么程序会在每个训练器后评估
络,并打印出部分进展。这对于追踪进度很有,但相当拖慢执速度。



















安全验证
文档复制为VIP权益,开通VIP直接复制

评论0