ModuleNotFoundError: No module named 'xgboost.sklearn' - python

I'm trying to import xgboost into jupyter-notebook but get the following error:
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-9-a585b270d0df> in <module>
1 import pandas as pd
2 import numpy as np
----> 3 import xgboost
~/.local/lib/python3.6/site-packages/xgboost/__init__.py in <module>
14 from . import tracker # noqa
15 from .tracker import RabitTracker # noqa
---> 16 from . import dask
17 try:
18 from .sklearn import XGBModel, XGBClassifier, XGBRegressor, XGBRanker
~/.local/lib/python3.6/site-packages/xgboost/dask.py in <module>
31 from .training import train as worker_train
32 from .tracker import RabitTracker
---> 33 from .sklearn import XGBModel, XGBClassifierBase, xgboost_model_doc
34
35 # Current status is considered as initial support, many features are
ModuleNotFoundError: No module named 'xgboost.sklearn'
I've downloaded sklearn as well as sci-kit learn and they work fine...
Any idea what the problem is?

You might need to install your packages properly.
For best practice, you'll need to use a conda environment. Check out how it works here: https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html
Once you have created your environment, activate it and then install all the packages you need. Presumably, you'll have to run the command:
conda install -c conda-forge xgboost
pip install -U scikit-learn
To install your machine learning packages.

XGBOOST is in xgboost module: It should be imported as:
`from xgboost import XGBRegressor`

Related

Windows VS Code can't find numpy Module even though it is installed (ModuleNotFoundError: No module named 'numpy.core._multiarray_umath')

I have been working with Anaconda and VS Code on my Windows and everything was fine until my computer once crashed. After that, I couldn't run my scripts that worked perfectly fine before.
For example, I now get the the error when running:
import os
import datetime
import IPython
import IPython.display
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from pmdarima import auto_arima
from kerastuner import HyperModel, Objective
from kerastuner import BayesianOptimization
import keras.backend as K
from tensorflow.keras.layers import (
Dense,
Dropout,
LSTM,
GRU
)
mpl.rcParams['figure.figsize'] = (8, 6)
mpl.rcParams['axes.grid'] = False
C:\Users\myname\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\__init__.py:138: UserWarning: mkl-service package failed to import, therefore Intel(R) MKL initialization ensuring its correct out-of-the box operation under condition when Gnu OpenMP had already been loaded by Python process is not assured. Please install mkl-service package, see http://github.com/IntelPython/mkl-service
from . import _distributor_init
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
~\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\core\__init__.py in <module>
21 try:
---> 22 from . import multiarray
23 except ImportError as exc:
~\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\core\multiarray.py in <module>
11
---> 12 from . import overrides
13 from . import _multiarray_umath
~\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\core\overrides.py in <module>
6
----> 7 from numpy.core._multiarray_umath import (
8 add_docstring, implement_array_function, _get_implementing_args)
ModuleNotFoundError: No module named 'numpy.core._multiarray_umath'
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-1-aaaeab3b7b86> in <module>
4 import IPython
5 import IPython.display
----> 6 import matplotlib as mpl
7 import matplotlib.pyplot as plt
8 import numpy as np
~\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\__init__.py in <module>
105 # cbook must import matplotlib only within function
106 # definitions, so it is safe to import from it here.
--> 107 from . import cbook, rcsetup
108 from matplotlib.cbook import MatplotlibDeprecationWarning, sanitize_sequence
109 from matplotlib.cbook import mplDeprecation # deprecated
~\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\cbook\__init__.py in <module>
26 import weakref
27
---> 28 import numpy as np
29
30 import matplotlib
~\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\__init__.py in <module>
138 from . import _distributor_init
139
--> 140 from . import core
141 from .core import *
142 from . import compat
~\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\core\__init__.py in <module>
46 """ % (sys.version_info[0], sys.version_info[1], sys.executable,
47 __version__, exc)
---> 48 raise ImportError(msg)
49 finally:
50 for envkey in env_added:
ImportError:
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.
We have compiled some common reasons and troubleshooting tips at:
https://numpy.org/devdocs/user/troubleshooting-importerror.html
Please note and check the following:
* The Python version is: Python3.9 from "C:\Users\myname\AppData\Local\Programs\Python\Python39\python.exe"
* The NumPy version is: "1.19.2"
and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.
Original error was: No module named 'numpy.core._multiarray_umath'
I have been reading multiple posts but couldn't find a solution. I tried multiple things:
I have uninstalled and reinstalled anconda
I have added C:\Users\myname\AppData\Local\Programs\Python\Python39 to my system variable path
use pip uninstall numpy and after that conda install numpy
set my python path in VS code to either C:\Users\myname\AppData\Local\Programs\Python\Python39 (pythn verison 3.9.4) or C:\Users\myname\anaconda3 (Python version 3.8.5)
I went to the link mentioned in the error message but couldn't find a solution
tried to upgarde my numpy version (I have 1.20.2)
(pip install numpy --upgrade
Requirement already up-to-date: numpy in c:\users\myname\anaconda3\lib\site-packages (1.20.2))
Python Verison: 3.8.5 and 3.9.4 (tried both)
Numpy Version: 1.20.1
Matplotlib Version: 3.4.1
This
import os
print(sys.version)
print("PYTHONPATH:", os.environ.get('PYTHONPATH'))
print("PATH:", os.environ.get('PATH'))
leads to this output:
3.9.4 (tags/v3.9.4:1f2e308, Apr 6 2021, 13:40:21) [MSC v.1928 64 bit (AMD64)]
PYTHONPATH: c:\Users\myname\.vscode\extensions\ms-toolsai.jupyter-2021.5.745244803\pythonFiles;c:\Users\myname\.vscode\extensions\ms-toolsai.jupyter-2021.5.745244803\pythonFiles\lib\python
PATH: C:\Users\myname\anaconda3;C:\Users\myname\anaconda3\Library\mingw-w64\bin;C:\Users\myname\anaconda3\Library\usr\bin;C:\Users\myanme\anaconda3\Library\bin;C:\Users\myname\anaconda3\Scripts;C:\Users\myname\anaconda3\bin;C:\Users\myname\anaconda3\condabin;C:\Users\myname\anaconda3;C:\Users\myname\anaconda3\Library\mingw-w64\bin;C:\Users\myname\anaconda3\Library\usr\bin;C:\Users\myname\anaconda3\Library\bin;C:\Users\myname\anaconda3\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C:\Program Files\MATLAB\R2020a\bin;C:\Users\myname\AppData\Local\Programs\Python\Python39;C:\Users\myname\AppData\Local\Microsoft\WindowsApps;C:\Users\myname\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\myname\AppData\Local\Programs\MiKTeX\miktex\bin\x64;C:\Users\myname\AppData\Local\Programs\Git\cmd;C:\Program Files (x86)\GitHub CLI;C:\Users\myname\AppData\Local\GitHubDesktop\bin
Thanks in advance for any help!
You have a lot going on here, including multiple installations of Python. It looks like you have both an Anaconda installation of Python, and a standard Python installation as well.
My first recommendation is to use virtual Python environments. These create isolated environments where you can install packages without worrying about messing up your base installation. There are a handful of ways to do this, Anaconda comes with Conda, and Python comes with venv. Both work well. I prefer Conda.
Step 1 - one or more of the packages in your standard Python installation are corrupted or incompatible; I would recommend uninstalling completely.
-- Windows Key > Settings (Gear icon) > Apps > Click on Python > Uninstall
Step 2 - assuming your Anaconda installation is not also corrupted, we can use Conda to create a new environment.
-- Windows Key > "Anaconda Prompt" > this opens a terminal with the base Anaconda environment.
conda create -n myenv python tensorflow ipython matplotlib pandas seaborn numpy -y
Step 3 - activate the environment to use it and install PyPi packages.
conda activate myenv
pip install pmdarima
Fells like magic, but after applying the steps mentioned by #James, restarting my laptop, disabling and reenabling all extensions in VS Code as well as setting the environment to myenv in Anaconda itself before launching VS Code, it finally works now. Don't know what exactly made the difference though. Thanks again #James for the help!

Error importing LGBMResgressor to lightgib

I'm getting the following error while importing LGBMResgressor to lightgbm:
ImportError
Traceback (most recent call last)
<ipython-input-38-1a53b4f7b770> in <module>()
5 from sklearn.kernel_ridge import KernelRidge
6 import lightgbm as lgb
----> 7 from lightgbm import LGBMRegressor
8 # from lightgbm.sklearn import LGBMRegressor
9 from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone
ImportError: cannot import name 'LGBMRegressor'
lightgbm's version is 2.0.5, and it is installed on Windows 10 by pip install lightgbm.
My environment is linux (python 3.6.1) and I installed with pip install lightgbm, opened a ipython terminal and copy your imports and not occurred error, but i can see an 'inconsistence' in your imports. On line six you make:
import lightgbm as lgb
And on the next line
from lightgbm import LGBMRegressor
On line 6 you already import all module as lgb (line 7 is unnecessary), for use LGBMRegressor just do:
lgb.LGBMRegressor
Finnaly, to make sure that the module are insalled, type in a command line:
python -c "import lightgbm; print(lightgbm.__version__)"
Output:
2.0.1

Tensorflow installation: ImportError on sklearn - undefined symbol: PyFPE_jbuf

Following the Udacity course on Deep Learning with TensorFlow, and hit a roadblock here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/1_notmnist.ipynb
I tried to get the installation running, but the initial imports didn't work out so well. Specifically, this import error on a certain file:
/tensorflow/lib/python2.7/site-packages/sklearn/linear_model/cd_fast.so
Running tensorflow in a virtualenv installation on Ubuntu 14.04, should that help.
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-3-72264e7a4df2> in <module>()
9 from IPython.display import display, Image
10 from scipy import ndimage
---> 11 from sklearn.linear_model import LogisticRegression
12 from six.moves.urllib.request import urlretrieve
13 from six.moves import cPickle as pickle
.../tensorflow/lib/python2.7/site-packages/sklearn/linear_model/__init__.py in <module>()
15 from .least_angle import (Lars, LassoLars, lars_path, LarsCV, LassoLarsCV,
16 LassoLarsIC)
---> 17 from .coordinate_descent import (Lasso, ElasticNet, LassoCV, ElasticNetCV,
18 lasso_path, enet_path, MultiTaskLasso,
19 MultiTaskElasticNet, MultiTaskElasticNetCV,
.../tensorflow/lib/python2.7/site-packages/sklearn/linear_model/coordinate_descent.py in <module>()
27 from ..utils import ConvergenceWarning
28
---> 29 from . import cd_fast
30
31
ImportError: .../tensorflow/lib/python2.7/site-packages/sklearn/linear_model/cd_fast.so: undefined symbol: PyFPE_jbuf
Anyone here who knows how to proceed? (Maybe this is a very simple error - I'm quite the newbie to this)
UPDATE:
Everything works fine when I run the iPython Notebooks from the usual terminal, as opposed to running them from the tensorflow virtual environment (as I had done when I first posted this question). I do not understand why this happened, though.
I also had trouble with sklearn in working with tensor flow. I had dowload it and install latest version manually to the TSNE module to work. Perhaps this will work for you too?
Step 1: Install Cython manually - you will version > 0.21
mkdir cython
cd cython
wget http://cython.org/release/Cython-0.24.zip
unzip Cython-0.24.zip
cd Cython-0.24
sudo python setup.py install
Step 2: Install latest version of skilearn

Cannot import sklearn in python

from sklearn import svm
I am getting the following error while importing sklearn modules.
/usr/lib/python2.7/dist-packages/scipy/sparse/linalg/isolve/iterative.py in <module>()
9
10 from scipy.sparse.linalg.interface import LinearOperator
---> 11 from scipy.lib.decorator import decorator
12 from .utils import make_system
13
ImportError: No module named decorator
ImportError Traceback (most recent call last)
<ipython-input-6-e938be4cf50b> in <module>()
----> 1 from sklearn import svm
/usr/local/lib/python2.7/dist-packages/sklearn/__init__.py in <module>()
54 # process, as it may not be compiled yet
55 else:
---> 56 from . import __check_build
57 from .base import clone
58 __check_build # avoid flakes unused variable error
ImportError: cannot import name __check_build
How to resolve this ?
I had the same error time ago, it is caused because either the machine doesn't have the scipy package installed, or it has the wrong distribution (depending on the architecture or OS).
If you have pip in your computer try installing scipy with:
sudo pip install scipy
If you have it already try upgrading or reinstalling the package.
Edit:
Following the solution suggested by #erip, you can create a virtual environmentand test the solution keeping your python global site-packages directory clean:
virtualenv test # This creates a folder with the virtual env
source test/bin/activate
pip install scipy
pip install sklearn
To deactivate and remove the virtual env:
deactivate
rm -r test # Remove the folder

scikit-learn 0.15.2 Python 3.4 Windows cannot import cluster [duplicate]

I am using scikit learn 0.15.0. When I try to import sklearn.mixture I get
ImportError: cannot import name choice
Any ideas?
===================================================================
In [1]: **from sklearn import mixture**
ImportError Traceback (most recent call last)
<ipython-input-1-05bc76cab98d> in <module>()
----> 1 from sklearn import mixture
/home/f/anaconda/lib/python2.7/site-packages/sklearn/mixture/__init__.py in <module>()
3 """
4
----> 5 from .gmm import sample_gaussian, log_multivariate_normal_density
6 from .gmm import GMM, distribute_covar_matrix_to_match_covariance_type
7 from .gmm import _validate_covars
/home/f/anaconda/lib/python2.7/site-packages/sklearn/mixture/gmm.py in <module>()
16 from ..utils import check_random_state, deprecated
17 from ..utils.extmath import logsumexp, pinvh
---> 18 from .. import cluster
19
20 from sklearn.externals.six.moves import zip
/home/f/anaconda/lib/python2.7/site-packages/sklearn/cluster/__init__.py in <module>()
4 """
5
----> 6 from .spectral import spectral_clustering, SpectralClustering
7 from .mean_shift_ import mean_shift, MeanShift, estimate_bandwidth, \
8 get_bin_seeds
/home/f/anaconda/lib/python2.7/site-packages/sklearn/cluster/spectral.py in <module>()
16 from ..neighbors import kneighbors_graph
17 from ..manifold import spectral_embedding
---> 18 from .k_means_ import k_means
19
20
/home/f/anaconda/lib/python2.7/site-packages/sklearn/cluster/k_means_.py in <module>()
28 from ..utils import as_float_array
29 from ..utils import gen_batches
---> 30 from ..utils.random import choice
31 from ..externals.joblib import Parallel
32 from ..externals.joblib import delayed
ImportError: cannot import name choice
from sklearn.mixture import GaussianMixture
using this would make it more specific to work with .gmm,
and
from sklearn.cluster import KMeans
for:
16 from ..neighbors import kneighbors_graph
17 from ..manifold import spectral_embedding
---> 18 from .k_means_ import k_means
As noted, it might have to do with old files (that are implemented in python as opposed to libraries?) in a new package you probably updated using pip install -U packagename (in my case pip install -U scikit-learn) It might be worth first trying to uninstall the package and install it again before manually deleting stuff... (worked in my case)
uninstall
(in my case run it on Anaconda Command prompt):
pip uninstall scikit-learn
then:
pip install -U numpy scipy scikit-learn
(added dependencies just in case)
then just to be sure
pip install scikit-learn
should say it's installed
I was getting the same error when I tried to import KMeans as : from sklearn.cluster import KMeans
Error > ImportError: cannot import name choice
I found the answer here: https://github.com/scikit-learn/scikit-learn/issues/3461
Since I have upgraded to Scikit version 0.15 a few days back, the older version of random.so was present in /usr/local/lib/python2.7/dist-packages/sklearn/utils.
I manually deleted it and now I do not get the error anymore.
Hope this helps.
New implementation is
from sklearn import mixture
model = mixture.GaussianMixture(n_components=3, covariance_type='full')
Just replace the first two lines

Categories