Attribute Error when trying to use PyTorch - pytorch

I am getting this error when trying to use PyTorch
import torch
z = torch.zeros(5,3)
print (z)
print(z.datatype)
AttributeError: partially initialized module 'torch' has no attribute 'zeros' (most likely due to a circular import)
I am on python 3.9 because PyTorch does not work with more modern versions
I tried reimporting with pip3 and it says that I already have it downloaded

Show a minimal, reproducible example
In an empty python program, show what is needed for any third party to replicate your problem.
This means:
import statement
just enough statements to trigger the error
And please state version of Pytorch as well as the version of Python that you did give.

Related

Import "tensorflow.keras" could not be resolved after upgrading to TensorFlow 2.8.0

TensorFlow 2.8 was recently released and I installed it as soon as it was out. I really need it for support of higher NumPy versions and a few new features. However, after installing it in my conda environment with
python3 -m pip install --upgrade tensorflow
neither PyCharm nor VSCode can no longer resolve the import from tensorflow.keras import ....
The imports themselves seem to work at runtime, but because the import cannot be resolved I can't make use of code completion, visualizing signatures of functions and etc. Has anybody encountered a similar issue?
everything was working with TF 2.7 - the version I had before.
Note: I'm using Python 3.8
Vs Code
PyCharm
I tried to check the versions through the PyCharm interpreter tab and this is what I saw. For some reason PyCharm isn't aware that there are versions after 2.0 (I have the latest version of pip installed in that environment). I'm guessing this is related, but not sure what to do with that.
I had the same problem and resolved it by importing it as
from tensorflow.python.keras.layers import Dense
This is a bug in the current version of tensorflow, as discussed in this issue.
You can work around it by either
modifying the file site-packages/tensorflow/__init__.py as described in this answer from the referenced issue or
using import keras.api._v2.keras as keras since this seems to be the exact package tensorflow loads itself. (Though you need to reference the protected member _v2 here, which is against python conventions.)
The reason here is that tensorflow tries to load the keras module in a lazy fashion, which means that it holds only a reference to the module until the module is used. Only then the keras module will be actually loaded. Therefore IDEs only know about the reference tensorflow holds to the keras module and not its content.
I see the problem in Google Colab as well. Although running the code works just fine. It's just an IDE complaint that supposedly it cannot find the imports. Very strange. I hope someone from the TensorFlow team gives feedback soon.
Resolving
import tensorflow
foo = tenstorflow.keras.foo
# if foo is a submodule but not an attribute, this will fail
and
from tensorflow.keras import foo
# if foo is an attribute, this is (roughly) equivalent to
import tensorflow.keras
foo = tenstorflow.keras.foo
# if foo is a submodule but not an attribute, this is (roughly) equivalent to
import tensorflow.keras.foo as foo
are different.
The first one need tensorflow has keras attribute with correct type statically during type checking.
But the second one need tensorflow.__path__ contains keras module statically during type checking.
BTW, for from tensorflow import keras:
If tensorflow has keras attribute, then it uses the attribute, otherwise it import keras as a submodule.
Theoretically, the second one should only work for 2.2.0 <= TF < 2.6.0, which has tensorflow/keras folder. Because tensorflow/keras should be removed in TF 2.6 according to TF 2.6 Release Log, otherwise from tensorflow import keras(tensorflow.keras backed by the keras PIP package) will be different from import tensorflow.keras as keras(tensorflow/keras backed by tensorflow/python/keras).
In fact, however, the second one works for 2.2.0 <= TF < 2.8.0, since tensorflow/keras is not removed until TF 2.8. Interestingly, tensorflow/python/keras is not removed yet (Release 2.9.1), violating the claim in TF 2.6 Release Log that "... will be removed in future release (2.7)".
The first one is broken for TF >= 2.5.0 because of keras lazy loading introduced in TF 2.5, and haven't been fixed yet (Release 2.9.1) though related commits have been merged into master branch.
See
https://github.com/tensorflow/tensorflow/pull/54104
and
https://github.com/tensorflow/tensorflow/commit/e65b68a0914408118995d2f8b55c4286859362f8
See also https://github.com/tensorflow/tensorflow/pull/54104#issuecomment-1067102133
This is happening to me in tensorflow-macos 2.10.0.
This has been a pattern as this post in GitHub shows. I'm getting the same. Ignoring it since the code still runs, but would rather not have the yellow. I hope someone from tensorflow can chime in. :)
This one worked for me:
from keras.utils.np_utils import to_categorical
You can create a symlink in tensorflow directory pointing to keras sources like below:
cd ./virtualenvs/myenv/lib/python3.x/site-packages/tensorflow
ln -s ../keras/api/_v2/keras/ keras

python 3.8 error with cross validation Implementation

When I run the following code from a tutorial, I keep getting the following error at the end in almost every video I attempt.
Source: https://pythonprogramming.net/k-means-from-scratch-2-machine-learning-tutorial/?completed=/k-means-from-scratch-machine-learning-tutorial/
I get the following error:
from sklearn import preprocessing, cross_validation
ImportError: cannot import name 'cross_validation' from 'sklearn
I did pip installs, changing the way cross_validation is stated based on other suggestions but I still can't solve it.
I could not find cross_validation as a library in sklearn.
You need to use from sklearn.model_selection import cross_validate as per the documentation. This has already been answered here.
I also suggest going through the documentation of the functions you use to gain a better understanding of what you are doing.

Onnx to mlmodel conversion fails to generate .mlmodel file

I'm trying to convert Pytorch model to MLModel with Onnx.
My code:
import torch
from onnx_coreml import convert
import coremltools
net = BiSeNet(19)
net.cuda()
net.load_state_dict(torch.load('model.pth'))
#net.eval()
dummy = torch.rand(1,3,512,512).cuda()
torch.onnx.export(net, dummy, "Model.onnx", input_names=["image"], output_names=["output"], opset_version=11)
finalModel = convert(model='Model.onnx', minimum_ios_deployment_target='12')
finalModel.save('ModelML.mlmodel')
After the code runs Model.onnx is generated, however, .mlmodel file is not generated. There're no errors in the console. This is the output:
2020-04-15 21:49:32.367179: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
WARNING:root:TensorFlow version 2.2.0-rc2 detected. Last version known to be fully compatible is 1.14.0 .
WARNING:root:Keras version 2.3.1 detected. Last version known to be fully compatible of Keras is 2.2.4 .
1.4.0
/content/drive/My Drive/Collab/fp/model.py:116: TracerWarning: Converting a tensor to a Python integer might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
size_array = [int(s) for s in feat32.size()[2:]]
/content/drive/My Drive/Collab/fp/model.py:80: TracerWarning: Converting a tensor to a Python integer might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
size_array = [int(s) for s in feat.size()[2:]]
/content/drive/My Drive/Collab/fp/model.py:211: TracerWarning: Converting a tensor to a Python integer might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
size_array = [int(s) for s in feat.size()[2:]]
What could be the issue?

Alternative to partial dependence plot?

as far as I can see, sklearn has deprecated the partial dependence functionality. I tried to run a simple example:
from sklearn.datasets import make_friedman1
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.inspection import partial_dependence
from sklearn.inspection import plot_partial_dependence
X, y = make_friedman1()
clf = GradientBoostingRegressor(n_estimators=10).fit(X, y)
plot_partial_dependence(clf, X, [0, (0, 1)])
But I am returned the following error message: ImportError: No module named 'sklearn.inspection'
To me, partial dependence (and marginal effects) plots a very important (in combination with relative importances) to better understand machine learning results and predictions.
Is there an alternative available? Respectively, how can I plot the partial dependence?
I think there might be a confusion with versions of sklearn. Just as a suggestion -- I would check yours (e.g., import sklearn; sklearn.__version__). For example, if it is v.0.20.3, by chance -- aren't you looking for partial_dependence and plot_partial_dependence from sklearn.ensemble.partial_dependence instead of sklearn.inspection?
I had the same issue, I resolved it by simply updating sklearn, which now contains sklearn.inspection. I'm using Anaconda, if you're also using Anaconda, simply type this in the Anaconda Propmt:
conda update --all
to update all packages. Restart your jupyter notebook and now it should work.

module 'sklearn.metrics' has no attribute 'davies_bouldin_score'

I am trying to evaluate a clustering kmeans model using sklearn.metrics.davies_bouldin_score. I am using google colab with runtime Python 3 and GPU accelerator.
I got this error:
module 'sklearn.metrics' has no attribute 'davies_bouldin_score'.
I have tried to import metrics package in different ways as it was suggested by some people as from sklearn import metrics and import sklearn.metrics. It made no difference.
I have also updated sklearn package !pip install --upgrade sklearn and it did not solve the problem.
Is it google-colaboratory? How can I solve it?
You need to pip install scikit-learn, not sklearn, though the import sklearn.metrics is correct. It looks like it's also a recently added feature, so it may not be available in earlier versions of scikit-learn.
It is in version 0.20. Make sure you are using the right version of Sklearn.
"conda update sklearn"

Resources