Python - cannot import `linalg` - python

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

Related

Attribute error: "module 'numpy.random' has no attribute 'uniform' "

Here are some of the things I tried to make it work
I've tried searching for any file named random.py that I created (except for library files) and searched online for solutions like updating numpy but still can't find any decent solution. Here is my code:
from numpy import random
import random
#from random import uniform
#inputs- i.e population
equation_inputs = [4,-2,3.5,5,-11,-4.7]
#number of weights
num_weights = 6
sol_per_pop = 9
pop_size = (sol_per_pop,num_weights)
#tuple of pop_size
new_population = numpy.random.uniform(low=-4.0,high=4.0,size=pop_size)
The error message goes as follows
AttributeError: module 'numpy.random' has no attribute 'uniform'
I tried importing random and also
from numpy import random
The numpy.random.uniform should actually return 9 lists each with 6 solutions
Just use random.uniform while importing the related class with an alias (using 'as') or else just use import numpy while importing
An example for using alias is :
from numpy import random as np_random
Then utilize np_random.uniform()

Dill installed - throwing error that part of the module is missing

I'm writing code in a Jupyter Notebook that involves cleaning and analyzing a large amount of consumer data. I'm trying to use dill to save the dataframes with thousands of rows so I don't have to run the code every time I want to make an adjustment, so dill seems like the perfect package to do so... Except I'm getting this error when attempting to pickle the notebook:
AttributeError: module 'dill' has no attribute 'dump_session'
Let me know if the program code is necessary - I don't think it should make a difference. The imports are:
import numpy as np
import pandas as pd
import dill
import scipy
from matplotlib import pyplot as plt
from __future__ import division
from collections import OrderedDict
from sklearn.cluster import KMeans
pd.options.display.max_columns = None
and when I run this code I get the error from above:
dill.dump_session('recengine.db')
Is there another package that's interfering with dill's use of pickle vs. cpickle?

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.

Tensorflow Module Import error: AttributeError: module 'tensorflow.python.ops.nn' has no attribute 'rnn_cell'

When attempting to pass my RNN call, I call tf.nn.rnn_cell and I receive the following error:
AttributeError: module 'tensorflow.python.ops.nn' has no attribute 'rnn_cell'
Which is odd, because I'm sure I imported everything correctly:
from __future__ import print_function, division
from tensorflow.contrib import rnn
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
But looking at the docs, things have moved around between tensorflow versions.
what would you all recommend to fix this??
Line, I'm getting the error against:
state_per_layer_list = tf.unstack(init_state, axis=0)
rnn_tuple_state = tuple(
[tf.nn.rnn_cell.LSTMStateTuple(state_per_layer_list[idx][0], state_per_layer_list[idx][1])
for idx in range(num_layers)]
)
Specifically:
tf.nn.rnn_cell
I'm using anaconda 3 to manage all of this so, the dependancies should all be taken care of. I have already tried working around a damn rank/shape error with Tensor shapes which took ages to resolve.
Cheers in advance.
Replace tf.nn.rnn_cell with tf.contrib.rnn
Since version 1.0, rnn implemented as part of the contrib module.
More information can be found here
https://www.tensorflow.org/api_guides/python/contrib.rnn

Hard time finding Python-Numpy deg2rad function

Title says it all, I somehow can not find that function. Obviously it's inside the Numpy package (numpy.core.umath.deg2rad) and I've tried importing it but to no avail. Anyone care to chime in?
import numpy as np - np.deg2rad doesn't even show up
from numpy import* - umath.deg2rad shows up, but it raises an error, ''name 'umath' is not defined''
from numpy.core.umath import deg2rad
# then
deg2rad(...)
Or
import numpy as np
np.core.umath.deg2rad(...)

Categories