Skip to content
This repository has been archived by the owner on Feb 28, 2024. It is now read-only.

using BayesSearchCV AttributeError module 'numpy' has no attribute 'int'. np.int was a deprecated alias for the builtin int. To avoid this error in existing code, use int by itself. Doing this will not modify any behavior and is safe. When replacing np.int, you may wish to use e.g. np.int64 or np.int32 to specify the precision. If you wish to review your current use, check the release note link for additional information. #1200

Open
zeron-G opened this issue Jan 17, 2024 · 4 comments

Comments

@zeron-G
Copy link

zeron-G commented Jan 17, 2024

when run bayes_cv.fit() get error

AttributeError module 'numpy' has no attribute 'int'. np.int was a deprecated alias for the builtin int. To avoid this error in existing code, use int by itself. Doing this will not modify any behavior and is safe. When replacing np.int, you may wish to use e.g. np.int64 or np.int32 to specify the precision. If you wish to review your current use, check the release note link for additional information.

it is due to the line opt.fit() that raises the error. More precisely, BayesSearchCV.fit() uses np.int. replaced all np.int with int in the file 'site-packages\skopt\space\transformers.py'

reference
https://stackoverflow.com/questions/76321820/how-to-fix-the-numpy-int-attribute-error-when-using-skopt-bayessearchcv-in-sci

@sushi3085
Copy link

Got same problem with the following code:

opt = BayesSearchCV(
    SVR(),
    {
        'C': (1e-6, 1e+6, 'log-uniform'),
        'gamma': (1e-6, 1e+1, 'log-uniform'),
        'degree': (1, 8),
        'kernel': ['linear', 'poly', 'rbf'],
    },
    n_iter=10,
    cv=5
)

opt.fit(trainX, trainY)  # RAISE AN ERROR AT THIS LINE

print("validation Score: ", opt.best_score_)
print("test score: ", opt.score(testX, testY))
AttributeError                            Traceback (most recent call last)
[~\AppData\Local\Temp/ipykernel_7760/3848764104.py](https://file+.vscode-resource.vscode-cdn.net/e%3A/Programming/pythonAI/sklearn/~/AppData/Local/Temp/ipykernel_7760/3848764104.py) in <module>
     14 )
     15 
---> 16 opt.fit(trainX, trainY)
     17 
     18 print("validation Score: ", opt.best_score_)

[d:\Python\lib\site-packages\skopt\searchcv.py](file:///D:/Python/lib/site-packages/skopt/searchcv.py) in fit(self, X, y, groups, callback, **fit_params)
    464             self.optimizer_kwargs_ = dict(self.optimizer_kwargs)
    465 
--> 466         super().fit(X=X, y=y, groups=groups, **fit_params)
    467 
    468         # BaseSearchCV never ranked train scores,

[d:\Python\lib\site-packages\sklearn\base.py](file:///D:/Python/lib/site-packages/sklearn/base.py) in wrapper(estimator, *args, **kwargs)
   1150                 )
   1151             ):
-> 1152                 return fit_method(estimator, *args, **kwargs)
   1153 
   1154         return wrapper

[d:\Python\lib\site-packages\sklearn\model_selection\_search.py](file:///D:/Python/lib/site-packages/sklearn/model_selection/_search.py) in fit(self, X, y, groups, **fit_params)
    896                 return results
...

AttributeError: module 'numpy' has no attribute 'int'.
`np.int` was a deprecated alias for the builtin `int`. To avoid this error in existing code, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.
The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at:
    https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations

I guess downgrade numpy to < 1.20 will fix this problem?

@zeron-G
Copy link
Author

zeron-G commented Jan 27, 2024

Got same problem with the following code:

opt = BayesSearchCV(
    SVR(),
    {
        'C': (1e-6, 1e+6, 'log-uniform'),
        'gamma': (1e-6, 1e+1, 'log-uniform'),
        'degree': (1, 8),
        'kernel': ['linear', 'poly', 'rbf'],
    },
    n_iter=10,
    cv=5
)

opt.fit(trainX, trainY)  # RAISE AN ERROR AT THIS LINE

print("validation Score: ", opt.best_score_)
print("test score: ", opt.score(testX, testY))
AttributeError                            Traceback (most recent call last)
[~\AppData\Local\Temp/ipykernel_7760/3848764104.py](https://file+.vscode-resource.vscode-cdn.net/e%3A/Programming/pythonAI/sklearn/~/AppData/Local/Temp/ipykernel_7760/3848764104.py) in <module>
     14 )
     15 
---> 16 opt.fit(trainX, trainY)
     17 
     18 print("validation Score: ", opt.best_score_)

[d:\Python\lib\site-packages\skopt\searchcv.py](file:///D:/Python/lib/site-packages/skopt/searchcv.py) in fit(self, X, y, groups, callback, **fit_params)
    464             self.optimizer_kwargs_ = dict(self.optimizer_kwargs)
    465 
--> 466         super().fit(X=X, y=y, groups=groups, **fit_params)
    467 
    468         # BaseSearchCV never ranked train scores,

[d:\Python\lib\site-packages\sklearn\base.py](file:///D:/Python/lib/site-packages/sklearn/base.py) in wrapper(estimator, *args, **kwargs)
   1150                 )
   1151             ):
-> 1152                 return fit_method(estimator, *args, **kwargs)
   1153 
   1154         return wrapper

[d:\Python\lib\site-packages\sklearn\model_selection\_search.py](file:///D:/Python/lib/site-packages/sklearn/model_selection/_search.py) in fit(self, X, y, groups, **fit_params)
    896                 return results
...

AttributeError: module 'numpy' has no attribute 'int'.
`np.int` was a deprecated alias for the builtin `int`. To avoid this error in existing code, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.
The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at:
    https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations

I guess downgrade numpy to < 1.20 will fix this problem?

that is because of BayesSearchCV.fit() function uses the np.int, you can go to skopt's library position and edit the 'the site-packages\skopt\space\transformers.py' by replacing all np.int with int it will fix
I pass the error by this method

@RNarayan73
Copy link

RNarayan73 commented Jan 29, 2024

A workaround that worked for me is to put these lines before fitting the estimator:

import numpy as np
np.int = int

@FlorinAndrei
Copy link

Another example that fails the same way.

Are there any plans to fix this bug? It's pretty old.

import numpy as np
import matplotlib.pyplot as plt
from warnings import filterwarnings
from skopt.plots import plot_convergence
from skopt import gp_minimize

filterwarnings('ignore')  # suppress some of the warnings from B.O.

np.random.seed(42)


# same "bumpy" function as in simulated annealing, just written differently
# assumes xy is a list or array-like with xy = [x, y]
def bumpy(xy):
    x = xy[0]
    y = xy[1]
    obj = (
        0.2
        + x**2
        + y**2
        - 0.1 * np.cos(6 * np.pi * x)
        - 0.1 * np.cos(6 * np.pi * y)
    )
    return obj


# call the optimization.
res = gp_minimize(
    bumpy,  # the function to minimize
    [(-1, 1), (-1, 1)],  # the bounds on each dimension of x
    acq_func="EI",  # the acquisition function
    n_calls=20,  # the number of evaluations of the objective function
    n_random_starts=5,  # the number of random initialization points
    random_state=42,
)  # the random seed

print(
    f'The minimum value of f(x) is {res.fun:0.4f} and occurs at x={res.x[0]:0.4f}, y={res.x[1]:0.4f}'
)
print(
    f'Recall that the objective function may include noise, so the optimized function value may not be exact.'
)

fig = plt.figure(
    figsize=(10, 6)
)  # we initialize the plot so we can control dimensions
ax = fig.add_axes
plot_convergence(res, ax)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants