【问题标题】:how to plot scipy optimize result如何绘制 scipy 优化结果
【发布时间】:2017-04-05 00:46:42
【问题描述】:

我使用函数 f(x) = sin(x) 进行了 python scipy 优化,我想绘制结果。我怎样才能做到这一点?我已经尝试过使用此代码。但我收到此错误:TypeError: only length-1 arrays can be converted to Python scalars

这是我的代码:

'''Import Python math library'''
import math
import matplotlib.pyplot as plt
'''try and except ImportError handler will be printing message if you haven't install required python library'''
try:
    import scipy.optimize as opt
    import scipy
    from scipy.optimize import minimize
except ImportError:
    print "You must install Python scipy first before running this program"

try:
    import numpy as np
except ImportError:
    print "You must install Python numpy first before running this program"

'''function f(x) = sin(x)'''
def f(x):
    print x
    #return -x**(2)
    return math.sin(x)

'''
check here for fmin_l_bgfs_b docs : https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_l_bfgs_b.html#scipy.optimize.fmin_l_bfgs_b
and what params need to used.

or you can take a look at here : https://docs.scipy.org/doc/scipy/reference/optimize.html for other method and algorithm
'''
initial_guess = 1.0

minbound = -9
maxbound = 9

max_bounds_area = (minbound,maxbound)
max_x = opt.fmin_l_bfgs_b(lambda x: -f(x), initial_guess, bounds=[(max_bounds_area)],approx_grad=True)

# I want to plot the result. I try this but I get TypeError: only length-1 arrays can be converted to Python scalars
t = np.arange(minbound, maxbound, initial_guess)
s = f(t)
plt.plot(t, s)
plt.show()

【问题讨论】:

    标签: python numpy scipy maximize


    【解决方案1】:

    math库不能对numpy arrays进行操作,必须使用numpy中实现的功能。

    必须改变

    return math.sin(x)
    

    return np.sin(x) 
    

    【讨论】:

    • 谢谢,它有效。但是我怎样才能使它具有平滑的曲线呢?
    • 比initial_guess小,是用于绘图的步长。即initial_guess=0.1
    • 感谢它与t = np.arange(minbound, maxbound, 0.1) 合作。非常感谢,我很感激。
    • 我需要等待 5 分钟才能接受这个作为正确答案。
    猜你喜欢
    • 2021-05-09
    • 2013-03-17
    • 1970-01-01
    • 2016-12-16
    • 2019-10-01
    • 2021-05-13
    • 2019-03-12
    • 2020-08-25
    • 1970-01-01
    相关资源
    最近更新 更多