0
0
SciPydata~10 mins

Optimization callbacks and monitoring in SciPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a callback function that prints the current iteration number during optimization.

SciPy
def callback(xk):
    print("Iteration:", [1])
Drag options to blanks, or click blank then click option'
Axk
Biteration
Cxk[0]
Dlen(xk)
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to print a variable not defined inside the function.
Using an undefined variable like 'iteration'.
2fill in blank
medium

Complete the code to call scipy.optimize.minimize with the callback function to monitor optimization.

SciPy
from scipy.optimize import minimize

result = minimize(func, x0, method='BFGS', [1]=callback)
Drag options to blanks, or click blank then click option'
Amonitor
Btrack
Cobserve
Dcallback
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect argument names like 'monitor' or 'track'.
3fill in blank
hard

Fix the error in the callback function to correctly count and print the iteration number.

SciPy
def callback(xk):
    callback.iteration = getattr(callback, 'iteration', 0) + [1]
    print(f"Iteration {callback.iteration}: {xk}")
Drag options to blanks, or click blank then click option'
A0
B1
Ccallback.iteration
Dxk
Attempts:
3 left
💡 Hint
Common Mistakes
Adding 0 instead of 1, causing iteration count to never increase.
4fill in blank
hard

Fill both blanks to create a callback that stops optimization after 5 iterations.

SciPy
def callback(xk):
    callback.count = getattr(callback, 'count', 0) + [1]
    if callback.count >= [2]:
        print('Stopping optimization')
        return True
Drag options to blanks, or click blank then click option'
A1
B5
C0
D10
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 to increment count, so count never increases.
Stopping at wrong iteration number.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that tracks parameter norms greater than 1 during optimization.

SciPy
norms = {i: [1] for i, x in enumerate(params) if [2] > [3]
Drag options to blanks, or click blank then click option'
Aabs(x)
C1
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Using raw x instead of abs(x), missing negative values.
Comparing x directly to 1 without abs.