Python中的深度学习 - 随机梯度下降 - 分解代码

时间:2018-03-28 13:21:15

标签: python python-3.x python-2.7 deep-learning

我试图基本上自己学习深度学习,使用我的大学提供的一些书籍Neural networks and Deep learning。 这个过程很难,而且由于我不习惯编码,一些问题已经出现了。例如,从下面的函数可以看出,链接的第1章提供了(我将代码从2.7更新到3.6)。

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 range(epochs):  #xrange was renamedto range
        random.shuffle(training_data)
        mini_batches = [
            training_data[k:k+mini_batch_size]
            for k in range(0, n, mini_batch_size)]  #xrange was renamedto range
        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))
            #print (self.biases)
            #print("Hello02")
        else:
            print ("Epoch {0} complete".format(j))

    return(self.biases, self.weights)

我的问题是这个问题:

if test_data: n_test = len(test_data)
n = len(training_data)

有谁可以向我解释这两行中发生了什么?我习惯了一个更传统的代码阶段,例如:

if something:
    print (another_thing)

1 个答案:

答案 0 :(得分:2)

也许我误解了你,但是:

if test_data:
    n_test = len(test_data)
n = len(training_data)

...的含义与:

相同
if test_data

此部分:if test_data is not None在语义上等同于if test_data != Nonerepmat

如果我误解了某事,请告诉我。)