Yousuf
Yousuf

Reputation: 13

np.max() error: TypeError: only integer scalar arrays can be converted to a scalar index

I'm trying to get the np.max() function to work like a relu() function but keep getting this error:

>>>np.max(0, np.arange(-5, 5))

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [91], in <cell line: 1>()
----> 1 np.max(0, np.arange(-5, 5))

File <__array_function__ internals>:5, in amax(*args, **kwargs)

File ~/opt/anaconda3/envs/coherence/lib/python3.10/site-packages/numpy/core/fromnumeric.py:2754, in amax(a, axis, out, keepdims, initial, where)
   2638 @array_function_dispatch(_amax_dispatcher)
   2639 def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
   2640          where=np._NoValue):
   2641     """
   2642     Return the maximum of an array or maximum along an axis.
   2643 
   (...)
   2752     5
   2753     """
-> 2754     return _wrapreduction(a, np.maximum, 'max', axis, None, out,
   2755                           keepdims=keepdims, initial=initial, where=where)

File ~/opt/anaconda3/envs/coherence/lib/python3.10/site-packages/numpy/core/fromnumeric.py:86, in _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs)
     83         else:
     84             return reduction(axis=axis, out=out, **passkwargs)
---> 86 return ufunc.reduce(obj, axis, dtype, out, **passkwargs)

TypeError: only integer scalar arrays can be converted to a scalar index

I want it to output [0, 0, 0, 0, 0, 0, 1, 2, 3, 4]

Upvotes: 1

Views: 1154

Answers (1)

Nick ODell
Nick ODell

Reputation: 25210

There are two similarly named numpy functions which do very different things:

  • np.max(), which is used to find the maximum of an array along a particular axis. So, if you wanted to find the largest element of a vector, you'd use this.
  • np.maximum(), which does an element-by-element maximum comparison, broadcasting if necessary. So, if you wanted to implement ReLU, you'd use this.

Example of how to implement ReLU:

>>> np.maximum(0, np.arange(-5, 5))
array([0, 0, 0, 0, 0, 0, 1, 2, 3, 4])

Upvotes: 3

Related Questions