v9.1.1
Menu

Hard Tanh

easyFREEActivation FunctionsDeep LearningDeep Learning 1

Problem Statement

Implement the "Hard Tanh" function which clamps values to a range.

Background

Hard Tanh is a computationally cheaper approximation of the tanh function:

  • Returns −1-1 if x<−1x < -1
  • Returns 11 if x>1x > 1
  • Returns xx if −1≤x≤1-1 \leq x \leq 1

It's essentially a piecewise linear function that clips values outside [-1, 1].

Your Task

Write a function hard_tanh(values) that applies Hard Tanh element-wise to a list.

Output Format

Return a list of floats with Hard Tanh applied. Round each value to 4 decimal places.

Example

Input
values=[-1.5, 0.5, 2.0]
Output
[-1.0, 0.5, 1.0]
Reasoning
  • Input: values is a list of real numbers, here three pre-activations: −1.5-1.5, 0.50.5 and 2.02.0. Each is treated independently.
  • Math: Hard Tanh is the piecewise function from the description: f(x)=−1f(x) = -1 for x<−1x < -1, f(x)=xf(x) = x for −1≤x≤1-1 \le x \le 1, and f(x)=1f(x) = 1 for x>1x > 1. It is the identity inside the band and flat outside it.
  • x=−1.5x = -1.5: it lies below the lower edge −1-1, so the output is pinned to −1.0-1.0.
  • x=0.5x = 0.5: it satisfies −1≤0.5≤1-1 \le 0.5 \le 1, so it passes through unchanged as 0.50.5 (already exact to 4 decimal places).
  • x=2.0x = 2.0: it exceeds the upper edge 11, so it is pinned to 1.01.0.
  • Output: a list of the same length, [-1.0, 0.5, 1.0], every entry a float in [−1,1][-1, 1]. Notice that the boundaries themselves stay put: f(−1)=−1f(-1) = -1 and f(1)=1f(1) = 1, while every input beyond the range, 22 or 10001000 alike, collapses to the same edge value.

Constraints

  • -1000 <= x <= 1000 for each element
  • List length: 1 to 100 elements

More from Deep Learning 1

solution.py

Test results

Sign in to run your code against the test cases.