Trouble Importing KMeans from Sklearn - python

I Have an error message when importing KMeans but I am able to import pandas and matplotlib.pyplot
Error Message is as follows:
TypeError Traceback (most recent call last)
File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/getlimits.py:649, in iinfo.__init__(self, int_type)
648 try:
--> 649 self.dtype = numeric.dtype(int_type)
650 except TypeError:
TypeError: 'NoneType' object is not callable
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
/Users/Downloads/Unclassified Learning/Unclassified Learning.ipynb Cell 27 in <cell line: 1>()
----> 1 from sklearn.cluster.KMeans import KMeans
File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/__init__.py:82, in <module>
80 from . import _distributor_init # noqa: F401
81 from . import __check_build # noqa: F401
---> 82 from .base import clone
83 from .utils._show_versions import show_versions
85 __all__ = [
86 "calibration",
87 "cluster",
(...)
128 "show_versions",
...
--> 651 self.dtype = numeric.dtype(type(int_type))
652 self.kind = self.dtype.kind
653 self.bits = self.dtype.itemsize * 8
TypeError: 'NoneType' object is not callable
I tried different variations of the code to import KMeans but still get the same error, would love to understand what is causing this. I have tried pip install -U scikit-learn and then the import but has this error instead:
TypeError Traceback (most recent call last)
File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/getlimits.py:649, in iinfo.__init__(self, int_type)
648 try:
--> 649 self.dtype = numeric.dtype(int_type)
650 except TypeError:
TypeError: 'NoneType' object is not callable
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
/Users/Downloads/Unclassified Learning/Unclassified Learning.ipynb Cell 27 in <cell line: 2>()
1 get_ipython().system('pip install -U scikit-learn')
----> 2 from sklearn.cluster import KMeans
File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/__init__.py:82, in <module>
80 from . import _distributor_init # noqa: F401
81 from . import __check_build # noqa: F401
---> 82 from .base import clone
83 from .utils._show_versions import show_versions
85 __all__ = [
86 "calibration",
87 "cluster",
(...)
...
--> 651 self.dtype = numeric.dtype(type(int_type))
652 self.kind = self.dtype.kind
653 self.bits = self.dtype.itemsize * 8
TypeError: 'NoneType' object is not callable
I have done this for other libraries and no issue so I am very lost, would appreciate any help!

Related

Error in importing shapefile in jupyter using geopanda

I am using Jupyter from Anaconda and trying to import a shapefile with following command line:
import geopandas as gpd
gdf = gpd.read_file('C:\Downloads\Temp\shapefile\regions.shp')
print (gdf)
gdf.plot()
However, I got following errors:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
Input In [7], in <cell line: 1>()
----> 1 gdf = gpd.read_file('C:\Downloads\Temp\shapefile\regions.shp')
2 print (gdf)
3 gdf.plot()
File C:\Anaconda3\lib\site-packages\geopandas\io\file.py:166, in _read_file(filename, bbox, mask, rows, **kwargs)
104 def _read_file(filename, bbox=None, mask=None, rows=None, **kwargs):
105 """
106 Returns a GeoDataFrame from a file or URL.
107
(...)
164 by using the encoding keyword parameter, e.g. ``encoding='utf-8'``.
165 """
--> 166 _check_fiona("'read_file' function")
167 filename = _expand_user(filename)
169 if _is_url(filename):
File C:\Anaconda3\lib\site-packages\geopandas\io\file.py:80, in _check_fiona(func)
78 def _check_fiona(func):
79 if fiona is None:
---> 80 raise ImportError(
81 f"the {func} requires the 'fiona' package, but it is not installed or does "
82 f"not import correctly.\nImporting fiona resulted in: {fiona_import_error}"
83 )
ImportError: the 'read_file' function requires the 'fiona' package, but it is not installed or does not import correctly.
Importing fiona resulted in: DLL load failed while importing ogrext: The specified module could not be found.
I have geopanda installed and not sure what is the problem.

"TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class" when importing the plotly.express library

I want to create a simple plotly chart from a .csv file that I fetched from an API.
I import the library, pass the dataframe, and get the error:
TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class
code:
import plotly.express as px
df=pd.read_csv('file.csv')
What might be the problem, and what does this error mean?
Full error traceback:
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9952/1054373791.py in <module>
1 from dash import Dash, dcc, html, Input, Output
----> 2 import plotly.express as px
3 import pandas as pd
~\anaconda3\lib\site-packages\plotly\express\__init__.py in <module>
13 )
14
---> 15 from ._imshow import imshow
16 from ._chart_types import ( # noqa: F401
17 scatter,
~\anaconda3\lib\site-packages\plotly\express\_imshow.py in <module>
9
10 try:
---> 11 import xarray
12
13 xarray_imported = True
~\anaconda3\lib\site-packages\xarray\__init__.py in <module>
----> 1 from . import testing, tutorial
2 from .backends.api import (
3 load_dataarray,
4 load_dataset,
5 open_dataarray,
~\anaconda3\lib\site-packages\xarray\testing.py in <module>
7 import pandas as pd
8
----> 9 from xarray.core import duck_array_ops, formatting, utils
10 from xarray.core.dataarray import DataArray
11 from xarray.core.dataset import Dataset
~\anaconda3\lib\site-packages\xarray\core\duck_array_ops.py in <module>
24 from numpy import where as _where
25
---> 26 from . import dask_array_compat, dask_array_ops, dtypes, npcompat, nputils
27 from .nputils import nanfirst, nanlast
28 from .pycompat import cupy_array_type, dask_array_type, is_duck_dask_array
~\anaconda3\lib\site-packages\xarray\core\npcompat.py in <module>
70 List[Any],
71 # anything with a dtype attribute
---> 72 _SupportsDType[np.dtype],
73 ]
74 except ImportError:
~\anaconda3\lib\typing.py in inner(*args, **kwds)
273 except TypeError:
274 pass # All real errors (not unhashable args) are raised below.
--> 275 return func(*args, **kwds)
276 return inner
277
~\anaconda3\lib\typing.py in __class_getitem__(cls, params)
997 else:
998 # Subscripting a regular Generic subclass.
--> 999 _check_generic(cls, params, len(cls.__parameters__))
1000 return _GenericAlias(cls, params)
1001
~\anaconda3\lib\typing.py in _check_generic(cls, parameters, elen)
207 """
208 if not elen:
--> 209 raise TypeError(f"{cls} is not a generic class")
210 alen = len(parameters)
211 if alen != elen:
TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class
I got the same error, it is dependency issue, plotly.express (5.9.0) is not working with numpy==1.20, if you upgrade numpy==1.21.6 it will solve your error.
pip install numpy==1.21.6
I was having same issue when I updated xarray. I tried updating numpy but conda environment was restricting it. Updating the whole conda environment helped me resolve this error.
conda update --all
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4960/3694415272.py in <module>
----> 1 plotly.express.__version__
~\anaconda3\lib\site-packages\_plotly_utils\importers.py in __getattr__(import_name)
37 return getattr(class_module, class_name)
38
---> 39 raise AttributeError(
40 "module {__name__!r} has no attribute {name!r}".format(
41 name=import_name, __name__=parent_name
AttributeError: module 'plotly' has no attribute 'express'

What should I do with this error in python when importing Paraview?

I finished the installation of Paraview by conda, but I got an attribute error when importing paraview.simple in jupyter notebook:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-56-51050ddfbc7e> in <module>
----> 1 import paraview.simple
~\Anaconda3\lib\site-packages\paraview\simple.py in <module>
39
40 import paraview
---> 41 from paraview import servermanager
42 import paraview._backwardscompatibilityhelper
43
~\Anaconda3\lib\site-packages\paraview\servermanager.py in <module>
3372 SetActiveConnection(activeConnection)
3373
-> 3374 __initialize()
3375
3376 if hasattr(sys, "ps1"):
~\Anaconda3\lib\site-packages\paraview\servermanager.py in __initialize()
3354 # Monitor connection creations/deletions on the ProcessModule.
3355 pm = vtkProcessModule.GetProcessModule()
-> 3356 pm.AddObserver("ConnectionCreatedEvent", __connectionCreatedCallback)
3357 pm.AddObserver("ConnectionClosedEvent", __connectionClosedCallback)
3358
AttributeError: 'paraview.modules.vtkRemotingCore.vtkProcessModule' object has no attribute 'AddObserver'
What should I do to fix it?

NumpyBackend' object has no attribute 'tucker'

I have some codes for doing image compression using svd and some more codes for experiments.
So I have the following code for experiment:
plt.figure(figsize=(20,12))
for i,rank in enumerate([2,10,20]):
plt.subplot(2,3,i+1)
plt.imshow(svd_compression(image1,rank))
plt.title("rank:%i - compression: %.2f%%" %(rank,svd_compress_ratio(image1,rank)*100))
for i,rank in enumerate([2,10,20]):
plt.subplot(2,3,i+4)
plt.imshow(svd_compression(image2,rank))
plt.title("rank:%i - compression: %.2f%%" %(rank,svd_compress_ratio(image2,rank)*100))
plt.show()
But I got the following errors:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorly/backend/__init__.py in _get_backend_method(key)
91 try:
---> 92 return getattr(_LOCAL_STATE.backend, key)
93 except AttributeError:
AttributeError: 'NumpyBackend' object has no attribute 'tucker'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
3 frames
/usr/local/lib/python3.6/dist-packages/tensorly/backend/__init__.py in _get_backend_method(key)
92 return getattr(_LOCAL_STATE.backend, key)
93 except AttributeError:
---> 94 return getattr(_LOADED_BACKENDS[_DEFAULT_BACKEND], key)
95
96 def _get_backend_dir():
AttributeError: 'NumpyBackend' object has no attribute 'tucker'
The method for compression is here:
!pip install tensorly
import numpy as np
import pylab as plt
import scipy.sparse.linalg
import PIL.Image
import tensorly as tl
import matplotlib.pyplot as plt2
from scipy.sparse.linalg import svds
def svd_compression(image, rank):
unfolded = tl.unfold(image, mode=0)
u, s, vt = svds(unfolded, rank)
return tl.fold(np.round(np.dot(u*s,vt),1), 0, image.shape) # need to round to have a color lvl

Theano step gives File in wrong format error

I am trying to replicate the example
Getting Started PyMC3.
on Windows 2012 R2.
The step
from pymc3 import Model, Normal, HalfNormal
gives
D:\Anaconda3\libs/python35.lib: error adding symbols: File in wrong format
collect2.exe: error: ld returned 1 exit status
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
D:\Anaconda3\lib\site-packages\theano\gof\lazylinker_c.py in <module>()
64 if version != getattr(lazylinker_ext, '_version', None):
---> 65 raise ImportError()
66 except ImportError:
ImportError:
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
D:\Anaconda3\lib\site-packages\theano\gof\lazylinker_c.py in <module>()
81 if version != getattr(lazylinker_ext, '_version', None):
---> 82 raise ImportError()
83 except ImportError:
ImportError:
During handling of the above exception, another exception occurred:
Exception Traceback (most recent call last)
<ipython-input-4-582c90a634a6> in <module>()
----> 1 from pymc3 import Model, Normal, HalfNormal
D:\Anaconda3\lib\site-packages\pymc3\__init__.py in <module>()
1 __version__ = "3.0"
2
----> 3 from .core import *
4 from .distributions import *
5 from .math import *
D:\Anaconda3\lib\site-packages\pymc3\core.py in <module>()
1 from .vartypes import *
----> 2 from .model import *
3 from .theanof import *
4 from .blocking import *
5 import numpy as np
D:\Anaconda3\lib\site-packages\pymc3\model.py in <module>()
1 from .vartypes import *
2
----> 3 from theano import theano, tensor as t, function
4 from theano.tensor.var import TensorVariable
5
D:\Anaconda3\lib\site-packages\theano\__init__.py in <module>()
53 object2, utils
54
---> 55 from theano.compile import \
56 SymbolicInput, In, \
57 SymbolicOutput, Out, \
D:\Anaconda3\lib\site-packages\theano\compile\__init__.py in <module>()
7 SpecifyShape, specify_shape, register_specify_shape_c_code)
8
----> 9 from theano.compile.function_module import *
10
11 from theano.compile.mode import *
D:\Anaconda3\lib\site-packages\theano\compile\function_module.py in <module>()
16 from theano import gof
17 from theano.compat.python2x import partial
---> 18 import theano.compile.mode
19 from theano.compile.io import (
20 In, SymbolicInput, SymbolicInputKit, SymbolicOutput)
D:\Anaconda3\lib\site-packages\theano\compile\mode.py in <module>()
9 import theano
10 from theano import gof
---> 11 import theano.gof.vm
12 from theano.configparser import config, AddConfigVar, StrParam
13 from theano.compile.ops import register_view_op_c_code, _output_guard
D:\Anaconda3\lib\site-packages\theano\gof\vm.py in <module>()
566
567 try:
--> 568 from . import lazylinker_c
569
570 class CVM(lazylinker_c.CLazyLinker, VM):
D:\Anaconda3\lib\site-packages\theano\gof\lazylinker_c.py in <module>()
115 args = cmodule.GCC_compiler.compile_args()
116 cmodule.GCC_compiler.compile_str(dirname, code, location=loc,
--> 117 preargs=args)
118 # Save version into the __init__.py file.
119 init_py = os.path.join(loc, '__init__.py')
D:\Anaconda3\lib\site-packages\theano\gof\cmodule.py in compile_str(module_name, src_code, location, include_dirs, lib_dirs, libs, preargs, py_module)
2008 # difficult to read.
2009 raise Exception('Compilation failed (return status=%s): %s' %
-> 2010 (status, compile_stderr.replace('\n', '. ')))
2011 elif config.cmodule.compilation_warning and compile_stderr:
2012 # Print errors just below the command line.
I have for gcc
C:\>gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=C:/TDM-GCC-64/bin/../libexec/gcc/x86_64-w64-mingw32/5.1.0/lt
o-wrapper.exe
Target: x86_64-w64-mingw32
Configured with: ../../../src/gcc-5.1.0/configure --build=x86_64-w64-mingw32 --e
nable-targets=all --enable-languages=ada,c,c++,fortran,lto,objc,obj-c++ --enable
-libgomp --enable-lto --enable-graphite --enable-cxx-flags=-DWINPTHREAD_STATIC -
-disable-build-with-cxx --disable-build-poststage1-with-cxx --enable-libstdcxx-d
ebug --enable-threads=posix --enable-version-specific-runtime-libs --enable-full
y-dynamic-string --enable-libstdcxx-threads --enable-libstdcxx-time --with-gnu-l
d --disable-werror --disable-nls --disable-win32-registry --prefix=/mingw64tdm -
-with-local-prefix=/mingw64tdm --with-pkgversion=tdm64-1 --with-bugurl=http://td
m-gcc.tdragon.net/bugs
Thread model: posix
gcc version 5.1.0 (tdm64-1)
what am i missing?
thanks
Whatever the issue was creating a python 3.4 environment together with
conda install mingw libpython
solved it.
What solved my issue is installing Python 2.7 version of anaconda
I got the same error using ipython. Using just python I imported theano without problem. Subsequent uses with ipython worked fine after the first compilation with just python.

Categories

Resources