无Python库实现向量梯度计算:代码报NameError问题求助
Hey there! Let's break down and fix the problems in your code one by one:
1. Why the NameError: x1 is not defined happens
In your function, you wrote:
x= (x1,x2)
This line tries to create a tuple using x1 and x2, but these variables haven’t been defined yet! Instead, you need to unpack the input tuple x (the (10,10) you pass when calling the function) into x1 and x2. The correct line should be:
x1, x2 = x
2. Incorrect Gradient Calculation
Your original gradient formulas don’t match the function f(x) = w1 * x1² + w2 * x2. Let’s re-derive the correct gradients with basic calculus:
- Derivative with respect to
x1:df/dx1 = 2 * w1 * x1(thew2*x2term has nox1, so its derivative is 0) - Derivative with respect to
x2:df/dx2 = w2(thew1*x1²term has nox2, so its derivative is 0)
Your original code had extra, incorrect terms (like w2 * x2 in gradx1 and w1 * x1^2 in gradx2) that need to be removed. Also, note that in Python, exponentiation uses **, not ^ (which is a bitwise XOR operator).
Corrected Full Code
Here’s the fixed version of your function:
def gradient(w1, w2, x): x1, x2 = x # Unpack the input tuple into x1 and x2 gradx1 = 2 * w1 * x1 gradx2 = w2 return (gradx1, gradx2)
Testing the Fixed Function
When you call gradient(5, 6, (10,10)), you’ll get the correct result:
print(gradient(5, 6, (10,10))) # Output: (100, 6)
Let’s verify:
gradx1 = 2*5*10 = 100gradx2 = 6— which perfectly matches the mathematical derivation.
内容的提问来源于stack exchange,提问作者Lillian

