未直接调用numpy却出现AttributeError: module 'numpy' has no attribute 'int'求助
np.int弃用导致的AttributeError问题 问题详情
我是新手程序员,运行LSTM超参数优化代码时,执行best_params = gp_minimize(lstm_objective, space, n_calls=15, random_state=0)语句出现报错:AttributeError: module 'numpy' has no attribute 'int',提示np.int已被弃用,但我的代码并未显式引入numpy。尝试重装、升级numpy均无效,恳请提供解决方案。
代码示例
# Step 6: Hyperparameter Optimization from skopt import gp_minimize from skopt.space import Real, Integer # Define hyperparameter search space space = [ Real(0.001, 0.1, name='learning_rate'), Integer(32, 128, name='batch_size'), Integer(50, 150, name='lstm_units'), Integer(1, 3, name='lstm_layers') ] # Define objective function def lstm_objective(params): # Unpack hyperparameters learning_rate = params[0] batch_size = params[1] lstm_units = params[2] lstm_layers = params[3] # Update LSTM model architecture model = Sequential() for i in range(lstm_layers): model.add(LSTM(units=lstm_units, return_sequences=True)) model.add(Dense(1)) # Compile and fit model.compile(optimizer=Adam(learning_rate), loss='mse') model.fit(X_train, y_train, batch_size=batch_size, epochs=10) # Evaluate MSE on validation set mse = model.evaluate(X_val, y_val, verbose=0) return mse # Run optimization best_params = gp_minimize(lstm_objective, space, n_calls=15, random_state=0) print(best_params.x)
报错信息
AttributeError: module 'numpy' has no attribute 'int'.
np.int是内置int的已弃用别名。要避免现有代码出错,直接用int即可,这不会改变任何行为,是安全的。替换np.int时,你可以考虑用np.int64或np.int32来指定精度。如需查看当前用法,可查看相关发布说明获取更多信息。
该别名最初在NumPy 1.20中被弃用。
解决方案
原因
你没有直接调用numpy,但你使用的scikit-optimize(skopt)或者Keras/TensorFlow等依赖库内部仍在使用已被弃用的np.int,和你本地安装的高版本numpy(1.20+)不兼容,从而触发报错。
方案1:降级numpy到兼容版本
安装numpy 1.19.x版本,该版本仍保留np.int别名,能快速解决兼容性问题:
pip install numpy==1.19.5
方案2:升级scikit-optimize到最新版
新版本的skopt大概率已经修复了这个numpy兼容性问题,执行升级命令:
pip install --upgrade scikit-optimize
方案3:手动修复依赖库代码
如果上述方案无效,可以找到skopt或相关依赖库中调用np.int的文件,将其替换为int或明确指定精度的np.int64/np.int32。比如在skopt的源码文件中全局搜索np.int,替换为int即可。
方案4:检查并升级Keras/TensorFlow
若你的LSTM模型依赖Keras/TensorFlow,旧版本框架也可能存在np.int的调用问题,升级到最新稳定版:
pip install --upgrade tensorflow keras
内容的提问来源于stack exchange,提问作者RED

