【问题标题】:How to put a 2*1 array in one line?如何将 2*1 数组放在一行中?
【发布时间】:2020-06-07 05:08:22
【问题描述】:

请不要告诉我将其重塑为 2*1,因为这会将第二个 [0.] 发送到下一行。我想要与预期输出相同的输出。 我想要完全相同的答案,并且使用 reshape 不是强制性的。

def initialize_with_zeros(dim):
    """
    This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.

    Argument:
    dim -- size of the w vector we want (or number of parameters in this 
    case)

    Returns:
    w -- initialized vector of shape (dim, 1)
    b -- initialized scalar (corresponds to the bias)
    """

    ### START CODE HERE ### (≈ 1 line of code)
    w = np.zeros((dim,1))
    b = 0
    ### END CODE HERE ###

    assert(w.shape == ( dim,1))
    assert(isinstance(b, float) or isinstance(b, int))

    return w, b

dim = 2
w, b = initialize_with_zeros(dim)

print ("w  " + str(w))
print ("b  " + str(b))

我得到的输出是:

w  [[ 0.]

 [ 0.]]

b  0

预期输出:

w       [[ 0.] [ 0.]]

b       0

【问题讨论】:

  • 你能把它作为代码块中的文本而不是屏幕图片发布吗?
  • 打印 w.tolist()

标签: python arrays pandas


【解决方案1】:

您需要使用reshape(-1, 1) 将 (2,) 转换为 (2,1)

import numpy as np

def initialize_with_zeros(dim):
    w = np.zeros(dim)
    b = 0
    return w, b

dim = 2
w,_ = initialize_with_zeros(dim)

w = w.reshape(-1, 1)

无需重塑:

array([0., 0.])

通过重塑:

array([[0.],
       [0.]])

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 2022-01-15
    • 1970-01-01
    • 2023-03-31
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    相关资源
    最近更新 更多