MikeJfromVA - 6 months ago 37

Python Question

The following syntax is very intuitive. Run in Spyder, and it plots a nonlinear function.

`import numpy as numpy`

import matplotlib.pyplot as plot

x = numpy.arange(0, 1, 0.01)

def nonlinear(x, deriv=False): #sigmoid

if (deriv==True):

return x*(1-x)

return 1/(1-numpy.exp(-x))

plot.plot(x, nonlinear(x))

My question is,

`nonlinear`

`plot.plot`

`nonlinear`

Answer

It works fine because the usual arithmetic operations (e.g. `/`

and `-`

as you've used) are defined for numpy arrays; they're just performed element-wise. The same goes for `np.exp()`

. You can see exactly what `nonlinear(x)`

looks like for yourself (it's also a numpy array):

```
>>> import numpy as np
>>> def nonlinear(x): return 1/(1 + np.exp(-x))
...
>>> nonlinear(np.arange(0, 1, 0.1))
array([ 0.5 , 0.52497919, 0.549834 , 0.57444252, 0.59868766,
0.62245933, 0.64565631, 0.66818777, 0.68997448, 0.7109495 ])
```

You're just finding the value of the sigmoid evaluated at each point in the specified range, and passing those as the y-values to `plot`

.

Source (Stackoverflow)