seul233 2022-03-31 07:28 采纳率: 0%
浏览 1358

python使用贝叶斯优化随机森林时出现TypeError: 'float' object is not subscriptable

问题遇到的现象和发生背景

在对随机森林调参的时候,出现了TypeError: 'float' object is not subscriptable

问题相关代码,请勿粘贴截图

代码如下

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
import matplotlib.pyplot as plt
data =  pd.read_csv("x.csv")
y =  pd.read_csv("y.csv")
feature = ['surface area(approx)','surface area(grid)','volume','hydration energy(kcal/mol)','logP','refractivity','polarizability','mass']
x = data[feature]
y = y['pIC50']
train_x, test_x, train_y, test_y = train_test_split(x, y,random_state=0,test_size=7)
model = RandomForestRegressor()
model = model.fit(train_x, train_y)
score = model.score(test_x, test_y)
print('默认参数下测试集评分:')
print(score)
def black_box_function(n_estimators, min_samples_split, max_features, max_depth):
    res = RandomForestRegressor(n_estimators=int(n_estimators),
                                min_samples_split=int(min_samples_split),
                                max_features=min(max_features, 0.999),  # float
                                max_depth=int(max_depth),
                                random_state=0
                                ).fit(train_x, train_y).score(test_x, test_y)
    return res
#确定域空间
pbounds= {'n_estimators': (1, 250),
         'min_samples_split': (2, 25),
         'max_features': (0.1, 0.999),
         'max_depth': (5, 25)}
from bayes_opt import BayesianOptimization
optimizer = BayesianOptimization(
        f=black_box_function,
        pbounds=pbounds,
        verbose=2,  # verbose = 1 prints only when a maximum is observed, verbose = 0 is silent
        random_state=0,
    )
optimizer.maximize(
        init_points=5,  #执行随机搜索的步数
        n_iter=25,   #执行贝叶斯优化的步数
    )
运行结果及报错内容
|   iter    |  target   | max_depth | max_fe... | min_sa... | n_esti... |
|  1        | -0.8974   |  15.98    |  0.743    |  15.86    |  136.7    |
|  2        | -0.7852   |  13.47    |  0.6807   |  12.06    |  223.1    |
|  3        | -1.096    |  24.27    |  0.4447   |  20.21    |  132.7    |
|  4        | -1.25     |  16.36    |  0.9321   |  3.634    |  22.7     |
|  5        | -1.08     |  5.404    |  0.8485   |  19.9     |  217.6    |
StopIteration                             Traceback (most recent call last)
File D:\python\lib\site-packages\bayes_opt\bayesian_optimization.py:179, in BayesianOptimization.maximize(self, init_points, n_iter, acq, kappa, kappa_decay, kappa_decay_delay, xi, **gp_params)
    178 try:
--> 179     x_probe = next(self._queue)
    180 except StopIteration:

File D:\python\lib\site-packages\bayes_opt\bayesian_optimization.py:25, in Queue.__next__(self)
     24 if self.empty:
---> 25     raise StopIteration("Queue is empty, no more objects to retrieve.")
     26 obj = self._queue[0]

StopIteration: Queue is empty, no more objects to retrieve.

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
Input In [9], in <cell line: 1>()
----> 1 optimizer.maximize(
      2         init_points=5,  #执行随机搜索的步数
      3         n_iter=25,   #执行贝叶斯优化的步数
      4     )

File D:\python\lib\site-packages\bayes_opt\bayesian_optimization.py:182, in BayesianOptimization.maximize(self, init_points, n_iter, acq, kappa, kappa_decay, kappa_decay_delay, xi, **gp_params)
    180 except StopIteration:
    181     util.update_params()
--> 182     x_probe = self.suggest(util)
    183     iteration += 1
    185 self.probe(x_probe, lazy=False)

File D:\python\lib\site-packages\bayes_opt\bayesian_optimization.py:131, in BayesianOptimization.suggest(self, utility_function)
    128     self._gp.fit(self._space.params, self._space.target)
    130 # Finding argmax of the acquisition function.
--> 131 suggestion = acq_max(
    132     ac=utility_function.utility,
    133     gp=self._gp,
    134     y_max=self._space.target.max(),
    135     bounds=self._space.bounds,
    136     random_state=self._random_state
    137 )
    139 return self._space.array_to_params(suggestion)

File D:\python\lib\site-packages\bayes_opt\util.py:65, in acq_max(ac, gp, y_max, bounds, random_state, n_warmup, n_iter)
     62     continue
     64 # Store it if better than previous minimum(maximum).
---> 65 if max_acq is None or -res.fun[0] >= max_acq:
     66     x_max = res.x
     67     max_acq = -res.fun[0]

TypeError: 'float' object is not subscriptable


我的解答思路和尝试过的方法

只出现了5组数据

我想要达到的结果

展开全部

  • 写回答

7条回答 默认 最新

  • weixin_48291099 2022-04-12 08:44
    关注

    请问楼主解决了吗?一模一样的问题

    评论
  • 代码好烫 2022-07-07 13:45
    关注

    问题已经解决了,详见参考链接:
    https://github.com/fmfn/BayesianOptimization/issues/300

    评论
  • CSDN专家-HGJ 2022-03-31 08:16
    关注

    类型错误,浮点数对象不能用下标引用。原因是在运行中调用源码时-res.fun[0]导致异常。其中的res.fun本来应该是一个列表(或元组或字符串)现在变成了一个浮点数,所以报错。从代码中排查可能导致这个错误的原因,检查参数设置的范围。

    评论
  • hellobigorange 人工智能领域新星创作者 2022-03-31 07:43
    关注

    检查一下你是不是哪里的索引用浮点型了,给他转成整形

    评论
  • 暮芸向铃 2022-04-06 09:59
    关注

    请问楼主解决了吗

    评论
  • 柠檬ya 2022-04-12 02:56
    关注

    我也是这个问题,前段时间没有,最近突然就变成这样了

    评论
  • weixin_46717578 2022-05-02 16:37
    关注
    评论
编辑
预览

报告相同问题?

问题事件

  • 创建了问题 3月31日

悬赏问题

  • ¥15 加热反应炉PLC控制系统设计(相关搜索:梯形图)
  • ¥15 python 用Dorc包报错,我的写法和网上教的是一样的但是它显示无效参数,是什么问题
  • ¥15 指定IP电脑的访问设置
  • ¥30 matlab ode45 未发现警告,但是运行出错
  • ¥15 vscode platformio
  • ¥15 代写uni代码,app唤醒
  • ¥15 全志t113i启动qt应用程序提示internal error
  • ¥15 ensp可以看看嘛.
  • ¥80 51单片机C语言代码解决单片机为AT89C52是清翔单片机
  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部