AttributeError:调用scipy优化器时,“设置”对象没有属性“获取”

如何解决AttributeError:调用scipy优化器时,“设置”对象没有属性“获取”

我正在尝试学习如何使用Scipys最小化器,但是执行时不断出现错误'set' object has no attribute 'get' 。该代码的其余部分似乎工作正常,并且除了拟合线l_fit之外,所有内容均已绘制。

很抱歉,很长的代码,但是我不知道可以删除什么来解决这个问题:

import pandas as pd
import matplotlib.pyplot as plt
import scipy.optimize as spo
import numpy as np

def error(line,data):
    err = np.sum((data[:,1] - (line[0] * data[:,0] + line[1])) ** 2)
    return err

def fit_line(data,error_func):

    # Generate initial guess for line model
    l= np.float32([0,np.mean(data[:,1])]) # slope = 0,intercept = mean( y values)
    
    # Plot initial guess
    x_ends = np.float32([-5,5])
    plt.plot(x_ends,l[0] * x_ends + l[1],'m--',linewidth=2.0,label="Initial guess")
    
    # Call optimizer to minimize error function
    result= spo.minimize(error_func,l,args=(data,),method='SLSQP',options={'display=true'})
    return result.x

def test_run():
    # define original line
    l_orig = np.float32([4,2])
    print("Original line: C0 = {},C1 = {}".format(l_orig[0],l_orig[1]))
    Xorig = np.linspace(0,10,21)
    Yorig = l_orig[0] * Xorig + l_orig[1]
    plt.plot(Xorig,Yorig,'b--',label='Original line')
    
    # Generate noisy data points
    noise_sigma= 3.0
    noise= np.random.normal(0,noise_sigma,Yorig.shape)
    data= np.asarray([Xorig,Yorig + noise]).T
    print(data)
    print(error)
    plt.plot(data[:,0],data[:,1],'go',label='Data points')
    
    # Try to fit a line to this data
    l_fit = fit_line(data,error)
    print("Fitted line: C0 = {},C1 = {}".format(l_fit[0],l_fit[1]))
    plt.plot(data[:,l_fit[0] * data[:,0] + l_fit[1],'r--',label="Fitted line")
    plt.show()

if __name__ == "__main__":
    test_run()

这是我的错误回溯:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-86b5f3cac3d8> in <module>
     56     # show plot
     57 if __name__ == "__main__":
---> 58     test_run()

<ipython-input-12-86b5f3cac3d8> in test_run()
     50 
     51     # Try to fit a line to this data
---> 52     l_fit = fit_line(data,error)
     53     print("Fitted line: C0 = {},l_fit[1]))
     54     plt.plot(data[:,label="Fitted line")

<ipython-input-12-86b5f3cac3d8> in fit_line(data,error_func)
     30 
     31     # Call optimizer to minimize error function
---> 32     result= spo.minimize(error_func,options={'display=true'})
     33     return result.x
     34 

~/opt/anaconda3/envs/futures/lib/python3.8/site-packages/scipy/optimize/_minimize.py in minimize(fun,x0,args,method,jac,hess,hessp,bounds,constraints,tol,callback,options)
    544     # - return_all
    545     if (meth in ('l-bfgs-b','tnc','cobyla','slsqp') and
--> 546             options.get('return_all',False)):
    547         warn('Method %s does not support the return_all option.' % method,548              RuntimeWarning)

AttributeError: 'set' object has no attribute 'get'

解决方法

问题是这条线

    result= spo.minimize(error_func,l,args=(data,),method='SLSQP',options={'display=true'})

具体为options={'display=true'},其类型为set,但是minimize要求类型为dict(根据documentation

可能您是说options={'display':True}吗?

提示:

print(type({'display=true'}))
print(type({'display':True}))

'display=true'是单个字符串变量。大括号{...}中的一个值或逗号分隔的值是set的简写,例如a={1,2,3}

dict相反,{}是空括号a={1:2,"a":"b"}或逗号分隔的键值对,例如library(dplyr) original %>% group_by(ID) %>% mutate( Number2 = if_else(Type=="Dead",last(Number[Type=="Live"]),NA_real_))

,

通过字典时,应遵循字典的语法 即{key:value} 在下面一行中将 options = {'display = true'} 更改为 options = {'display':True} ,它应该可以按照您的期望工作。

result= spo.minimize(error_func,options={'display=true'})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res