Gradient descent on a bowl

A stretched bowl has one steep direction and one gentle direction, which makes the choice of learning rate matter.

What to build

Run gradient descent on f(x, y) = (x − p)² + k(y − q)² until the gradient is small.

Requirements

  • Start at (x0, y0) and repeat (x, y) ← (x, y) − rate × gradient.
  • Count the steps taken. Stop when the gradient length is below tol.
  • Print diverged if the length exceeds 1e12, or no convergence after 10000 steps.
  • Otherwise print the number of steps and the final point with 4 decimal places.

Input

Line 1: p, q and k. Line 2: x0, y0, rate and tol. All numbers are decimals and k is positive.

Output

Either diverged, no convergence, or two lines: steps N and point X Y with 4 decimal places.

Constraints

All numbers are between -100 and 100, tol is between 0.000001 and 1, and the rate is positive.

Example

Input:

1 2 1
5 5 0.1 0.001

Output:

steps 42
point 1.0003 2.0003

Why it works

In the x direction each step multiplies the error by 1 − 2·rate, and in the y direction by 1 − 2k·rate. The method converges only when both factors lie between −1 and 1, so the steep direction (large k) limits the learning rate.

Examples

Example 1 · Input
1 2 1
5 5 0.1 0.001
Expected output
steps 42
point 1.0003 2.0003
Example 2 · Input
0 0 3
2 -1 0.1 0.0001
Expected output
steps 48
point 0.0000 0.0000

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

For f = (x − p)² + k·(y − q)² the gradient is (2(x − p), 2k(y − q)).

Hint 2

Before each step, compute the gradient length sqrt(gx² + gy²). Stop if it is below tol.

Hint 3

If the length ever exceeds 1e12, print `diverged` and stop. Also stop after 10000 steps with `no convergence`.

Solution

Show one correct solution (try it yourself first)
from math import sqrt

p, q, k = [float(v) for v in input().split()]
x, y, rate, tol = [float(v) for v in input().split()]

steps = 0
result = None
while True:
    gx, gy = 2 * (x - p), 2 * k * (y - q)
    length = sqrt(gx * gx + gy * gy)
    if length < tol:
        break
    if length > 1e12:
        result = "diverged"
        break
    if steps >= 10000:
        result = "no convergence"
        break
    x, y = x - rate * gx, y - rate * gy
    steps += 1
if result:
    print(result)
else:
    print("steps", steps)
    print(f"point {round(x, 4) + 0.0:.4f} {round(y, 4) + 0.0:.4f}")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Gradients and gradient descent →