L1 and L2 weight penalties

Regularization charges a model for its weights. Compute both standard charges.

What to build

A program that computes the L1 and L2 penalties of a list of weights.

Requirements

  • L1 = λ × Σ |w|.
  • L2 = λ × Σ w².
  • Print L1 A and L2 B, with 4 decimal places.

Input

Line 1: λ. Line 2: the weights.

Output

Two lines.

Constraints

1 to 1000 weights; λ ≥ 0.

Example

Input:

0.1
3 -4

Output:

L1 0.7000
L2 2.5000

Why it works

Both penalties grow with the size of the weights, so adding them to the loss makes training prefer smaller weights; squaring punishes the largest weights the most.

Examples

Example 1 · Input
0.1
3 -4
Expected output
L1 0.7000
L2 2.5000
Example 2 · Input
1
0.5
Expected output
L1 0.5000
L2 0.2500

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

Hints

Hint 1

L1 adds up the absolute values of the weights; L2 adds up their squares.

Hint 2

Multiply each sum by λ.

Solution

Show one correct solution (try it yourself first)
lam = float(input())
weights = list(map(float, input().split()))
print(f"L1 {lam * sum(abs(w) for w in weights):.4f}")
print(f"L2 {lam * sum(w * w for w in weights):.4f}")

Lesson: Regularization: ridge, lasso and early stopping →