【问题标题】:I am getting “IndentationError: expected an indented block” in np.random.seed(2). How to fix this?我在 np.random.seed(2) 中收到“IndentationError: expected an indented block”。如何解决这个问题?
【发布时间】:2020-02-18 19:35:40
【问题描述】:
import numpy as np
def initialize_parameters(n_x, n_h, n_y):

    np.random.seed(2) # we set up a seed so that our output matches ours although the initialization is random.

    W1 = np.random.randn(n_h, n_x) * 0.01 #weight matrix of shape (n_h, n_x)
    b1 = np.zeros(shape=(n_h, 1))  #bias vector of shape (n_h, 1)
    W2 = np.random.randn(n_y, n_h) * 0.01   #weight matrix of shape (n_y, n_h)
    b2 = np.zeros(shape=(n_y, 1))  #bias vector of shape (n_y, 1)

    #store parameters into a dictionary    
    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}

    return parameters

#Function to define the size of the layer
def layer_sizes(X, Y):
    n_x = X.shape[0] # size of input layer
    n_h = 6# size of hidden layer
    n_y = Y.shape[0] # size of output layer
    return (n_x, n_h, n_y)

但出现此错误: 文件“”,第 4 行 np.random.seed(2) # 我们设置了一个种子,以便我们的输出与我们的匹配,尽管初始化是随机的。 ^ IndentationError: 需要一个缩进块

【问题讨论】:

  • 应该在你的函数中的代码需要缩进。这就是python如何知道属于函数的代码
  • 我将您的帖子编辑为应该如何缩进。只需确保函数/类/等内部的东西。正确缩进
  • 你声明了一个函数第 2 行,所以你必须缩进属于这个函数的行。如果函数应该是空的,目前,您可以添加一个“路径”作为主体
  • @Chrispresso 应该是评论或答案,而不是对问题的编辑。以这种方式编辑只会导致提问者、评论者和答案之间的混淆

标签: python numpy backpropagation


【解决方案1】:

一切来自:

def initialize_parameters(n_x, n_h, n_y):

return parameters

在上面的示例中需要缩进四个空格。即,这个:

def initialize_parameters(n_x, n_h, n_y):

np.random.seed(2) # we set up a seed so that our output matches ours although the initialization is random.

W1 = np.random.randn(n_h, n_x) * 0.01 #weight matrix of shape (n_h, n_x)
b1 = np.zeros(shape=(n_h, 1))  #bias vector of shape (n_h, 1)
W2 = np.random.randn(n_y, n_h) * 0.01   #weight matrix of shape (n_y, n_h)
b2 = np.zeros(shape=(n_y, 1))  #bias vector of shape (n_y, 1)

#store parameters into a dictionary    
parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}

return parameters

应该这样格式化:

def initialize_parameters(n_x, n_h, n_y):

    np.random.seed(2) # we set up a seed so that our output matches ours although the initialization is random.

    W1 = np.random.randn(n_h, n_x) * 0.01 #weight matrix of shape (n_h, n_x)
    b1 = np.zeros(shape=(n_h, 1))  #bias vector of shape (n_h, 1)
    W2 = np.random.randn(n_y, n_h) * 0.01   #weight matrix of shape (n_y, n_h)
    b2 = np.zeros(shape=(n_y, 1))  #bias vector of shape (n_y, 1)

    #store parameters into a dictionary    
    parameters = {
        "W1": W1,
        "b1": b1,
        "W2": W2,
        "b2": b2
    }

    return parameters

(我将parameters 字典格式作为奖励加入了;))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    相关资源
    最近更新 更多