Skip to main content
 首页 » 编程设计

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

2024年12月31日7bonelee

以下是基于 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) 被明确地用于确保如果它确实包含任何冗余轴,则将其删除。