pythonnumpynumpy-ndarraydeprecation-warning

Trying to fix a NumPy asscalar deprecation issue


While trying to update an old Python script I ran into the following error:

module 'numpy' has no attribute 'asscalar'. Did you mean: 'isscalar'?

Specifically:

def calibrate(x, y, z):
  # H = numpy.array([x, y, z, -y**2, -z**2, numpy.ones([len(x), 1])])
  H = numpy.array([x, y, z, -y**2, -z**2, numpy.ones([len(x)])])
  H = numpy.transpose(H)
  w = x**2
  
  (X, residues, rank, shape) = linalg.lstsq(H, w)
  
  OSx = X[0] / 2
  OSy = X[1] / (2 * X[3])
  OSz = X[2] / (2 * X[4])
  
  A = X[5] + OSx**2 + X[3] * OSy**2 + X[4] * OSz**2
  B = A / X[3]
  C = A / X[4]
  
  SCx = numpy.sqrt(A)
  SCy = numpy.sqrt(B)
  SCz = numpy.sqrt(C)
  
  # type conversion from numpy.float64 to standard python floats
  offsets = [OSx, OSy, OSz]
  scale = [SCx, SCy, SCz]
  
  offsets = map(numpy.asscalar, offsets)
  scale = map(numpy.asscalar, scale)
  
  return (offsets, scale)

I found that asscalar has been deprecated since NumPy 1.16. I found one reference that said to use numpy.ndarray.item, but I have no clue how to do that.

I did try this:

offsets = map.item(offsets)
scale = map.item( scale)

but got this error:

AttributeError: type object 'map' has no attribute 'item'

How can I solve this?


Solution

  • Just replace numpy.scalar using numpy.ndarray.item, that is, change

    offsets = map(numpy.asscalar, offsets)
    scale = map(numpy.asscalar, scale)
    

    to

    offsets = map(numpy.ndarray.item, offsets)
    scale = map(numpy.ndarray.item, scale)