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

无Python库实现向量梯度计算:代码报NameError问题求助

Fixing Your Gradient Calculation Code & NameError Issue

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 (the w2*x2 term has no x1, so its derivative is 0)
  • Derivative with respect to x2: df/dx2 = w2 (the w1*x1² term has no x2, 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 = 100
  • gradx2 = 6 — which perfectly matches the mathematical derivation.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 14:42:41