Skip to content
DeepForgeby svx
All problems
EasyOptimizationop-021

Gradient Clipping By Value

Problem

Clip every gradient component to the interval [-clip_value, clip_value].

Return a new list where each component g becomes clip_value if g is too large, -clip_value if it is too small, and otherwise stays unchanged. An empty input returns [].

Hint

Clamp each component independently; no scaling is involved.

Test cases

case 1
in: [[1.5,-0.5,0,5],1]
expected: [1,-0.5,0,1]
case 2
in: [[0.4,-0.6],1]
expected: [0.4,-0.6]
case 3
in: [[3,-4],2.5]
expected: [2.5,-2.5]
case 4
in: [[],1]
expected: []
Starter codePython
def clip_by_value(grads, clip_value):
    # Your code here
    pass

4 test cases · run your code against them in the editor