Can not access ConvexHull in Scipy 0.16.1 - python

I was able to use the ConvexHull function in previous versions of Scipy. The function, in the version I had, would not provide the Volume of the convex hull so I decided to install the new version of Scipy. But after installing Scipy 0.16.1 I noticed that the Spatial library is rearranged and now I get an error when trying to call ConvexHull function.
This code would work in previous versions of Scipy:
import numpy as np
import scipy as sp
X = np.random.randint(0,200,(30,2))
hull = sp.spatial.qhull.Delaunay(X).convex_hull
Now, for the code above, I get the error:
AttribureError: 'module' object has no attribute 'spatial'.
It seems there is nothing inside .qhull.
I have checked this in VS,Spider,Ubuntu

You have to explicitly import the spatial subpackage. This should work:
import numpy as np
import scipy as sp
import scipy.spatial
X = np.random.randint(0,200,(30,2))
hull = sp.spatial.qhull.Delaunay(X).convex_hull

Related

'function' object has no attribute 'fft2' error scipy

I am struggling with an error called 'function' object has no attribute 'fft2'. First of all,
I have imported the following:
import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy import fft
After executing the following block of code in jupyter notebook:
gainDisplay=1
InImgFFT=fft.fft2(InImg,norm="ortho")
InImgAmplSpec=np.abs(fft.fftshift(InImgFFT))
plt.figure(figsize=(W/DPI+1,H/DPI+1))
plt.imshow(np.clip(InImgAmplSpec*gainDisplay,0,255),cmap = 'rainbow')
plt.suptitle('The amplitude spectrum of the gray scale input image')
plt.show()
I get the error mentioned at the line with fft.fft2() function
Could you please help me to solve this error?
scipy version is 1.5.2
Another mention would be that I have a conda environment where i have installed all the packets, but I hope that won't be a problem.

Error in importing module of python library scipy

I am working on clustering in python. The package I want to import is
from scipy.spatial.distance import dist
but this is showing the following error.
ImportError: cannot import name 'dist' from 'scipy.spatial.distance' (C:\Users\majid\Anaconda3\lib\site-packages\scipy\spatial\distance.py)
Instead of importing dist you need to import pdist or cdist based on your requirement as per the SciPy documentation:
pdist(X[, metric])
Pairwise distances between observations in n-dimensional space.
cdist(XA, XB[, metric])
Compute distance between each pair of the two collections of inputs.

Python - cannot import `linalg`

I have this code
import scipy.sparse as sparse
import numpy as np
id = np.eye(13)
vals, vecs = sparse.linalg.eigsh(id, k=6)
vals
which is just the example code from the documentation here.
I am running it in a Python 2.7 console and I get the following error message:
AttributeError: 'module' object has no attribute 'linalg'
Does anyone know why this happens?
Try this code
import scipy.sparse.linalg as sp
import numpy as np
id = np.eye(13)
vals, vecs = sp.eigsh(id, k=6)
vals
This happens because linalg is a directory and not source code i.e it is a sub-package. And I guess this causes the issue because some of the Scipy sub modules do not have __init__.py, Maybe the devs did this to reduce loading times of top-level packages. You can find this information in Scipy Organization section in this link

wavedec does not returning any coefficients in python using pywt library

i used wavelet decomposition command in python using pywt library but it does not return any coefficients. my code is given below .
import numpy as np
import pywt as pywt
(e,f)=pywt.wavedec(y,'db12' ,level=2)
print("e:"+str(e))
print("f:"+str(f))
I also tried with pywt.dwt(y,' db12', level=2) it is also not returning any coefficients
it returns a null output, where y is a matrix contains my input
I tried reproducing your results with a random (discrete) signal like so:
import numpy as np
import pyw
x = np.random.randint(0,100,500)
y = pywt.wavedec(x, 'db12', level=2)
(e,f) = pywt.dwt(x, 'db12')
I noticed two things: For a 1D signal, wavedec returns more than two coefficient arrays, as also mentioned in the docs. Similarly, the dwt function does not know the keyword level=, but works just fine with the command specified above.
Hope that helps

Running glmnet with rpy2 on sparse design matrix?

I have a python snippet which works just fine to run GLMNET on np.array X and y. However, when X is a column sparse matrix from scipy, the code fails as rpy2 is not able to convert X. Am I making an obvious mistake?
A MCVE is:
import numpy as np
from scipy import sparse
from rpy2 import robjects
import rpy2.robjects.packages as rpackages
from rpy2.robjects import numpy2ri
from rpy2.robjects import pandas2ri
if __name__ == "__main__":
X = sparse.rand(5, 20, density=0.1)
y = np.random.randn(5)
numpy2ri.activate()
pandas2ri.activate()
utils = rpackages.importr('utils')
utils.chooseCRANmirror(ind=1)
if not rpackages.isinstalled('glmnet'):
utils.install_packages("glmnet")
glmnet = rpackages.importr('glmnet')
glmnet = robjects.r['glmnet']
glmnet_fit = glmnet(X, y, intercept=False, standardize=False)
And when I run it I get a NotImplementedError:
Conversion 'py2ri' not defined for objects of type '<class 'scipy.sparse.csc.csc_matrix'>'
Could I provide X in a different way? I'd be surprised if rpy2 could not handle sparse matrices.
You can create a sparse matrix with rpy2 as follows:
import numpy as np
import rpy2.robjects as ro
from rpy2.robjects.packages import importr
from scipy import sparse
X = sparse.rand(5, 20, density=0.1).tocoo()
r_Matrix = importr("Matrix")
r_Matrix.sparseMatrix(
i=ro.IntVector(X.row + 1),
j=ro.IntVector(X.col + 1),
x=ro.FloatVector(X.data),
dims=ro.IntVector(X.shape))
There is indeed no converter Python -> R for your object type included in rpy2. Your Python object is not a conventional arrays but a sparse matrix as you note it (scipy.sparse.csc.csc_matrix to be specific), implemented as one of the numerical extensions available for numpy. As numpy itself is not even required to use rpy2 the support for extension of numpy is rather sparse, at the notable exception of pandas since data tables are ubiquitous.
You may want to write your own converter from css_matrix to gcCMatrix in the R package Matrix (https://stat.ethz.ch/R-manual/R-devel/library/Matrix/html/dgCMatrix-class.html) as the package glmnet appears to be able to handle them.
Writing a custom converter will require how to map or copy the content of the Python object to its chosen R counterpart, but once done plugging the code into rpy2 should be quite easy:
https://rpy2.github.io/doc/v2.9.x/html/generated_rst/s4class.html#custom-conversion
Consider opening an issue as a "feature request" on the rpy2 issue tracker, and reporting progress and outcome, with the hope to see this turn into a pull request complete with unit tests
Also a quick solution that might work would be to save the sparse matrix file temporarily.
import numpy as np
import rpy2.robjects as ro
import warnings
from rpy2.rinterface import RRuntimeWarning
import rpy2.robjects.numpy2ri as numpy2ri
from scipy.io import mmwrite
mmwrite('temp.mtx',matrix)
ro.r('X <- readMM("temp.mtx")')
I would be very interested though, if someone comes with a custom converter for avoiding that copy to disk.

Categories