MATLAB のものに似た Pythonのheaviside関数はありheaviside
ますか?
私はそれを見つけるのに苦労しています。
numpyバージョン1.13.0以降を使用している場合は、次を使用できますnumpy.heaviside
。
In [61]: x
Out[61]: array([-2. , -1.5, -1. , -0.5, 0. , 0.5, 1. , 1.5, 2. ])
In [62]: np.heaviside(x, 0.5)
Out[62]: array([ 0. , 0. , 0. , 0. , 0.5, 1. , 1. , 1. , 1. ])
古いバージョンのnumpyでは、次のように実装できます0.5 * (numpy.sign(x) + 1)
In [65]: 0.5 * (numpy.sign(x) + 1)
Out[65]: array([ 0. , 0. , 0. , 0. , 0.5, 1. , 1. , 1. , 1. ])
おそらく最も簡単な方法は
def step(x):
return 1 * (x > 0)
これは、単一の数値と numpy 配列の両方で機能し、整数を返し、x = 0 の場合はゼロですstep(0) => 0.5
。特定の状況では、最後の基準の方が望ましい場合があります。
これはsympyの一部であり、インストールできますpip install sympy
ドキュメントから:
class sympy.functions.special.delta_functions.Heaviside
Heaviside Piecewise function. Heaviside function has the following properties:
1) diff(Heaviside(x),x) = DiracDelta(x) ( 0, if x<0 )
2) Heaviside(x) = < [*] 1/2 if x==0 ( 1, if x>0 )
次のように使用します。
In [1]: from sympy.functions.special.delta_functions import Heaviside
In [2]: Heaviside(1)
Out[2]: 1
In [3]: Heaviside(0)
Out[3]: 1/2
In [4]: Heaviside(-1)
Out[4]: 0
自分で書くこともできます:
heaviside = lambda x: 0.5 if x == 0 else 0 if x < 0 else 1
ただし、シンボリック変数が必要な場合は、ニーズを満たさない場合があります。
すぐに使えるかどうかはわかりませんが、いつでも書くことができます:
def heaviside(x):
if x == 0:
return 0.5
return 0 if x < 0 else 1
def heaviside(xx):
return numpy.where(xx <= 0, 0.0, 1.0) + numpy.where(xx == 0.0, 0.5, 0.0)
または、numpy.where
が遅すぎる場合:
def heaviside(xx):
yy = numpy.ones_like(xx)
yy[xx < 0.0] = 0.0
yy[xx == 0.0] = 0.5
return yy
次のタイミングは numpy 1.8.2 のものです。numpy 1.9.0 でいくつかの最適化が行われたので、自分で試してみてください:
>>> import timeit
>>> import numpy
>>> array = numpy.arange(10) - 5
>>> def one():
... return numpy.where(array <= 0, 0.0, 1.0) + numpy.where(array == 0.0, 0.5, 0.0)
...
>>> def two():
... yy = numpy.ones_like(array)
... yy[array < 0] = 0.0
... yy[array == 0] = 0.5
... return yy
...
>>> timeit.timeit(one, number=100000)
3.026144027709961
>>> timeit.timeit(two, number=100000)
1.5265140533447266
>>> numpy.__version__
'1.8.2'
別のマシンで、別の numpy を使用:
>>> timeit.timeit(one, number=100000)
0.5119631290435791
>>> timeit.timeit(two, number=100000)
0.5458788871765137
>>> numpy.__version__
'1.11.1'
>>> def three():
... return 0.5*(numpy.sign(array) + 1)
...
>>> timeit.timeit(three, number=100000)
0.313539981842041
簡単な解決策:
import numpy as np
amplitudes = np.array([1*(x >= 0) for x in range(-5,6)])