gpt4 book ai didi

python - np.squeeze() 用于实现成本函数和梯度

转载 作者:太空宇宙 更新时间:2023-11-04 04:23:28 25 4
gpt4 key购买 nike

以下是基于 Coursera 深度学习类(class)计算成本函数和梯度以便对图像进行分类的代码。

计算成本如下

cost = -np.sum(Y*np.log(A) + (1-Y)*np.log(1-A)) / m 

cost.shape

()

那么下面操作的目的是什么

cost = np.squeeze(cost)

在函数中

def propagate(w, b, X, Y):
"""
Implement the cost function and its gradient for the propagation

Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (num_px * num_px * 3, number of examples)
Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)

Return:
cost -- negative log-likelihood cost for logistic regression
dw -- gradient of the loss with respect to w, thus same shape as w
db -- gradient of the loss with respect to b, thus same shape as b

"""
m = X.shape[1]

# FORWARD PROPAGATION (FROM X TO COST)
A = sigmoid(np.dot(w.T, X) + b) # compute activation
cost = -np.sum(Y*np.log(A) + (1-Y)*np.log(1-A)) / m # compute cost

# BACKWARD PROPAGATION (TO FIND GRAD)
dw = np.dot(X, (A-Y).T) / m
db = np.sum(A-Y) / m

assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)
assert(cost.shape == ())

grads = {"dw": dw,
"db": db}

return grads, cost

最佳答案

np.squeeze用于移除numpy.ndarray中带有Singleton元素的轴。例如,如果你有一个形状为 (n,m,1,p) 的 numpy 数组 a,那么 np.squeeze(a)将使形状成为 (n,m,p),减少第三个轴,因为它只有一个元素。

这里,cost 应该是一个单一的值。虽然它是 () 形状的 np.ndarray,但在计算自身之后,一个额外的步骤 np.squeeze(a) 被明确地用于确保如果它确实包含任何冗余轴,则将其删除。

关于python - np.squeeze() 用于实现成本函数和梯度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53981560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com