[英]how to extract value from a numpy.ndarray
我正在使用Scipy.Optimize.fmin来查找函数的最大值。 输出为numpy.ndarray的形式,其中包含有关该进程的其他信息。 我只需要将x值作为浮点数返回即可。
def f(x):
"""returns the value of f(x) with the input value x"""
import math
f = math.exp(-x ** 2.0) / (1.0 + x ** 2.0) + \
2.0 * (math.cos(x) ** 2.0) / (1.0 + (x - 4.0) ** 2.0)
return f
def find_max_f():
"""returns the x for which f(x) takes the maximum value"""
import scipy.optimize as o
m = o.fmin(lambda x: -f(x), 0)
return m
这是返回的内容:
>>> find_max_f()
Optimization terminated successfully.
Current function value: -1.118012
Iterations: 12
Function evaluations: 24
array([ 0.0131875])
我只需要标记为数组的方括号内的最终数字
只需将结果绑定到某些东西,然后就可以索引第一个元素,就好像它是列表或元组一样:
>>> xopt = find_max_f()
Optimization terminated successfully.
Current function value: -1.118012
Iterations: 12
Function evaluations: 24
>>> xopt
array([ 0.0131875])
>>> xopt[0]
0.013187500000000005
>>> type(xopt[0])
<type 'numpy.float64'>
我建议阅读NumPy教程 ,尤其是有关“索引,切片和迭代”的部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.