[PYTHON] Rewrite piecewise of NumPy for CuPy

NumPy piecewise

A piecewise function of NumPy can be realized.

f(x) = \left\{
\begin{array}{ll}
x^2 & (x \geq 0) \\
0 & (x \lt 0)
\end{array}
\right.

This is written piecewise as follows.

import numpy as np

x = np.arange(-4, 5)
np.piecewise(x, [x >= 0, x < 0], [lambda v: v ** 2, 0])

When you do this,

array([ 0,  0,  0,  0,  0,  1,  4,  9, 16])

Will be. It is the square of x in the range of x> = 0, and 0 in the range of x <0.

How to not use piesewise

CuPy does not support piecewise (as of v7.2), so it will be described in another way. .. Write without using if statements with poor performance.

It's easy to write, just add up the result of multiplying the classification condition and the function value.

import cupy as cp

x = cp.arange(-4, 5)
positive_condition = x >= 0
positive_value = x ** 2
negative_condition = x < 0
negative_value = 0
positive_condition * positive_value + negative_condition * negative_value

When you do this,

array([ 0,  0,  0,  0,  0,  1,  4,  9, 16])

And the same result as piecewise.

This way of writing is of course valid in NumPy.

Recommended Posts

Rewrite piecewise of NumPy for CuPy
Calculation speed of indexing for numpy quadratic array
About all of numpy
Set function of NumPy
Comparison of color detection methods in OpenCV inRange, numpy, cupy
Sum of multiple numpy arrays (sum)
About all of numpy (2nd)
Percentage of LIKE for pymysql
Overview of Docker (for beginners)
Implementation of Scale-space for SIFT
Output csv with different number of digits for each column with numpy