You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DeepLearning.AI课程1第2周propagate函数TypeError报错求助

Fixing the TypeError in Your Logistic Regression Propagate Function

Hey there! Let's break down the error you're hitting and get your propagate function working correctly for the DeepLearning.AI course.

What's Causing the TypeError?

The TypeError: can only concatenate tuple (not "float") to tuple comes down to a simple parentheses mistake in how you calculate the activation A:

A = sigmoid(np.dot((w.T,X)+b))

By wrapping w.T and X in parentheses like (w.T,X), you're creating a tuple instead of passing two separate arrays to np.dot. When you try to add the float b to this tuple, Python throws an error because tuples and floats can't be added together.

On top of that, there are two small tweaks needed to get the rest of the function working as expected:

  1. When calculating dw, you used dot() instead of np.dot() — Python's built-in dot isn't designed for matrix multiplication like numpy's version is.
  2. The axis=1 in your cost calculation is unnecessary (and could cause dimension issues later) since we need to sum all elements across all samples, not just along a specific axis.

Corrected Propagate Function

Here's the fixed code with clear explanations for each change:

# GRADED FUNCTION: propagate
def propagate(w, b, X, Y):
    """
    Implement the cost function and its gradient for the propagation explained above
    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
    
    Tips:
    - Write your code step by step for the propagation. np.log(), np.dot()
    """
    
    m = X.shape[1]
    
    # FORWARD PROPAGATION (FROM X TO COST)
    ### START CODE HERE ### (≈ 2 lines of code)
    # Fixed: Calculate dot product first, then add b (no extra parentheses around w.T and X)
    A = sigmoid(np.dot(w.T, X) + b)                                # compute activation
    # Fixed: Removed axis=1 to sum all elements, matching the cost function formula
    cost = -1/m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))  # compute cost
    ### END CODE HERE ###
    
    # BACKWARD PROPAGATION (TO FIND GRAD)
    ### START CODE HERE ### (≈ 2 lines of code)
    # Fixed: Used np.dot() instead of dot() to ensure numpy matrix multiplication
    dw = 1/m * np.dot(X, (A - Y).T)
    db = 1/m * np.sum(A - Y)
    ### END CODE HERE ###
    
    assert(dw.shape == w.shape)
    assert(db.dtype == float)
    cost = np.squeeze(cost)
    assert(cost.shape == ())
    
    grads = {"dw": dw, "db": db}
    
    return grads, cost

Test It Out

When you run your original test code now:

w, b, X, Y = np.array([[1.],[2.]]), 2., np.array([[1.,2.,-1.],[3.,4.,-3.2]]), np.array([[1,0,1]])
grads, cost = propagate(w, b, X, Y)
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
print ("cost = " + str(cost))

You'll get the correct output:

dw = [[0.99845601]
 [2.39507239]]
db = 0.001455578136784208
cost = 5.801545319394553

Quick Additional Notes

  • For the activation A, numpy automatically broadcasts the scalar b to match the shape of np.dot(w.T, X), so you don't have to worry about dimension mismatches here.
  • The dw calculation uses np.dot(X, (A-Y).T) to ensure the output shape matches w: since X is (n,m) and (A-Y).T is (m,1), the result is (n,1), which matches the shape of w.

内容的提问来源于stack exchange,提问作者Nawaf Momin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:10:13